alielie
2025-08-25 c4a3f8db90530a727ffab77c3bb5bb7d782792bf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
using HMI.Base;
using HMI.Core.Entity;
using HMI.Core.Setting;
using HMI.Core.Util;
using HMI.UI.DpUtil;
using HMI.UI.Util;
using log4net;
using Panuon.WPF.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using WPFProject.Utils;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
 
namespace WPFProject
{
    public class LoginException : Exception
    {
        public LoginException(string message) : base(message)
        {
        }
    }
 
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : WindowX
    {
        private ILog log;
        public Login()
        {
            log = LogManager.GetLogger("Login");
            InitializeComponent();
        }
 
        private static readonly Encryptor encryptor = new Encryptor("aB3dE5fG7hI9jjK1lMnOpQrS2tUvWxYz",
            "8Wq9RsT4vYx6ZuB1");
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (FormGroupHelper.ValidateForm(formPanel))
            {
                ButtonHelper.SetIsPending(BtnLogin, true);
                string username = TbAccount.Text;
                string password = PwdPassword.Password;
                bool rememberMe = SwRememberMe.IsChecked == true;
                Task.Run(() =>
                {
                    DoLogin(username, password, rememberMe);
                });
            }
        }
 
        private List<PermissionData> SelectPermission(string username, SqliteHelper sqliteHelper, out List<PermissionData> allPermission)
        {
            List<PermissionData> data = new List<PermissionData>();
            allPermission = new List<PermissionData>();
            Dictionary<string, PermissionData> cache = new Dictionary<string, PermissionData>();
            try
            {
                string sql = $@"SELECT DISTINCT m.* FROM menu AS m INNER JOIN role_menu_rel AS rrel ON m.code = rrel.menuCode
INNER JOIN role AS r ON rrel.roleCode = r.code
INNER JOIN user_role_rel AS urel ON r.code = urel.roleCode
AND urel.username = '{username}' ORDER BY m.level,m.sort, m.id;";
 
                DataTable dt = sqliteHelper.GetDataTable(sql);
                if (dt != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string path = Path.Combine(PathHelper.IconFolder, dr["iconPath"].ToString());
                        var menu = new PermissionData
                        {
                            Code = dr["code"].ToString(),
                            Name = dr["name"].ToString(),
                            Type = dr["type"].ToString(),
                            ParentCode = dr["parentCode"].ToString(),
                            DllPath = dr["dllPath"].ToString(),
                            ClassName = dr["className"].ToString(),
                            IconFont = dr["icon"].ToString()
                        };
                        cache[menu.Code] = menu;
                        allPermission.Add(menu);
                        if (!cache.ContainsKey(menu.ParentCode))
                        {
                            data.Add(menu);
                        }
                        else
                        {
                            cache[menu.ParentCode].Children.Add(menu);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //LoadMessageAppend?.Invoke(this, ex.Message);
            }
            return data;
        }
 
        private void DoLogin(string username, string password, bool rememberMe)
        {
            try
            {
                using (SqliteHelper helper = new SqliteHelper(PathHelper.DatabasePath))
                {
                    string sql = $"SELECT id,code,username,password,name From user WHERE username='{username}' and password='{password}'";
                    DataTable dt = helper.GetDataTable(sql);
                    if (dt == null || dt.Rows.Count <= 0)
                    {
                        throw new LoginException(LangUtil.Get("App.ErrorUsernameOrPassword"));
                    }
                    List<PermissionData> permissions = SelectPermission(username, helper, out List<PermissionData> allPermission);
                    UserInfo user = new UserInfo(
                        dt.Rows[0]["id"].ToString(),
                        dt.Rows[0]["code"].ToString(),
                        dt.Rows[0]["username"].ToString(),
                        dt.Rows[0]["name"].ToString(),
                        permissions,
                        allPermission,
                        dt.Rows[0]["password"].ToString()
                    );
 
                    UserInfo.Login(user);
                    if (rememberMe)
                    {
                        // 记住登录操作
                        string userToken =
                            JsonUtil.Serialize(
                                new UserInfo(null, user.Code, user.Username, user.Name, null, null,
                                dt.Rows[0]["password"].ToString()));
                        // 存储数据
                        BinUtil.SaveStrToBin(encryptor.Encrypt(userToken),
                            Path.Combine(PathHelper.DatabaseFolder, "user.bin"));
                    }
 
                    Dispatcher.Invoke(() =>
                    {
                        LoadingWindow loading = new LoadingWindow();
                        loading.Show();
                        this.Closed -= window_Closed;
                        this.Close();
                    });
                }
            }
            catch (Exception ex)
            {
                if (!(ex is LoginException)) log.Error("Login Failed.", ex);
                Dispatcher.Invoke(() =>
                {
                    ToastHelper.Error(this, $"{LangUtil.Get("App.LoginFailed")}: {ex.Message}");
                });
            }
            finally
            {
 
                Dispatcher.Invoke(() =>
                {
                    ButtonHelper.SetIsPending(BtnLogin, false);
                });
            }
        }
 
        /// <summary>
        /// 渲染完成后,尝试自动登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowX_ContentRendered(object sender, EventArgs e)
        {
            string userToken = string.Empty;
            if (BinUtil.LoadStrFromBin(ref userToken, Path.Combine(PathHelper.DatabaseFolder, "user.bin")))
            {
                userToken = encryptor.Decrypt(userToken);
                UserInfo userInfo = JsonUtil.Deserialize<UserInfo>(userToken);
                TbAccount.Text = userInfo.Username;
                PwdPassword.Password = userInfo.Password;
                SwRememberMe.IsChecked = true;
                Button_Click(null, null);
            }
        }
        private void window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }
 
        private void SwRememberMe_Unchecked(object sender, RoutedEventArgs e)
        {
            string path = Path.Combine(PathHelper.DatabaseFolder, "user.bin");
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
    }
}