From f3d3358b819fde9eb11fe04f5cb7726c5e1bf96c Mon Sep 17 00:00:00 2001 From: Argo-MacBookPro Date: Fri, 7 Sep 2018 15:53:16 +0800 Subject: [PATCH] =?UTF-8?q?=E9=87=8D=E6=9E=84=E4=BB=A3=E7=A0=81=EF=BC=9A?= =?UTF-8?q?=E9=87=8D=E6=96=B0=E7=BC=96=E5=86=99header=20nav=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E6=8B=89=E5=8E=BB=E6=96=B9=E5=BC=8F=EF=BC=8C=E4=BC=98?= =?UTF-8?q?=E5=85=88=E4=BD=BF=E7=94=A8WebSocket=E7=84=B6=E5=90=8E=E4=BD=BF?= =?UTF-8?q?=E7=94=A8WebLoop=E6=96=B9=E5=BC=8F=EF=BC=8C=E9=87=8D=E6=9E=84?= =?UTF-8?q?=E6=96=B0=E7=94=A8=E6=88=B7=E6=B3=A8=E5=86=8C=E3=80=81=E6=89=B9?= =?UTF-8?q?=E5=A4=8D=E3=80=81=E6=8B=92=E7=BB=9D=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/Api/NewController.cs | 29 ++- .../Controllers/Api/UsersController.cs | 22 +- .../Controllers/Api/WSController.cs | 23 +++ Bootstrap.Admin/Startup.cs | 2 +- Bootstrap.Admin/appsettings.json | 9 +- Bootstrap.Admin/wwwroot/js/common-scripts.js | 46 ++--- Bootstrap.Admin/wwwroot/js/longbow.common.js | 195 ++++++++++++------ Bootstrap.Admin/wwwroot/js/noti.js | 7 +- Bootstrap.Admin/wwwroot/js/profiles.js | 6 +- Bootstrap.DataAccess/NotificationHelper.cs | 147 ++----------- Bootstrap.DataAccess/User.cs | 30 ++- Bootstrap.DataAccess/UserHelper.cs | 70 +++++-- Bootstrap.DataAccess/WSHelper.cs | 19 ++ DatabaseScripts/Procedures.sql | 57 +---- 14 files changed, 351 insertions(+), 311 deletions(-) create mode 100644 Bootstrap.Admin/Controllers/Api/WSController.cs create mode 100644 Bootstrap.DataAccess/WSHelper.cs diff --git a/Bootstrap.Admin/Controllers/Api/NewController.cs b/Bootstrap.Admin/Controllers/Api/NewController.cs index 41855f05..299fa029 100644 --- a/Bootstrap.Admin/Controllers/Api/NewController.cs +++ b/Bootstrap.Admin/Controllers/Api/NewController.cs @@ -13,7 +13,7 @@ namespace Bootstrap.Admin.Controllers public class NewController : Controller { /// - /// + /// 登录页面注册新用户remote validate调用 /// /// /// @@ -23,13 +23,36 @@ namespace Bootstrap.Admin.Controllers { return BootstrapUser.RetrieveUserByUserName(userName) == null && !UserHelper.RetrieveNewUsers().Any(u => u.UserName == userName); } + /// + /// 登录页面注册新用户提交按钮调用 + /// + /// + /// [HttpPost] [AllowAnonymous] public bool Post([FromBody] User user) + { + var ret = UserHelper.SaveUser(user); + if (ret) NotificationHelper.PushMessage(new MessageBody() { Category = "Users", Message = string.Format("{0}-{1}", user.UserName, user.Description) }); + return ret; + } + /// + /// 新用户授权/拒绝接口 + /// + /// + [HttpPut("{id}")] + public bool Put([FromBody]User value) { var ret = false; - if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password) || string.IsNullOrEmpty(user.DisplayName) || string.IsNullOrEmpty(user.Description)) return ret; - return UserHelper.SaveUser(user); + if (value.UserStatus == UserStates.ApproveUser) + { + ret = UserHelper.ApproveUser(value.Id, User.Identity.Name); + } + else if (value.UserStatus == UserStates.RejectUser) + { + ret = UserHelper.RejectUser(value.Id, User.Identity.Name); + } + return ret; } } } \ No newline at end of file diff --git a/Bootstrap.Admin/Controllers/Api/UsersController.cs b/Bootstrap.Admin/Controllers/Api/UsersController.cs index 7f67c7d8..4f9fb256 100644 --- a/Bootstrap.Admin/Controllers/Api/UsersController.cs +++ b/Bootstrap.Admin/Controllers/Api/UsersController.cs @@ -5,6 +5,7 @@ using Longbow.Web.Mvc; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; +using System; using System.Collections.Generic; using System.Linq; @@ -36,15 +37,15 @@ namespace Bootstrap.Admin.Controllers.Api if (User.IsInRole("Administrators")) return false; var ret = false; - if (value.UserStatus == 3) + if (value.UserStatus == UserStates.ChangeTheme) { return UserHelper.SaveUserCssByName(value.UserName, value.Css); } if (value.UserName.Equals(User.Identity.Name, System.StringComparison.OrdinalIgnoreCase)) { - if (value.UserStatus == 1) + if (value.UserStatus == UserStates.ChangeDisplayName) ret = BootstrapUser.SaveUserInfoByName(value.UserName, value.DisplayName); - else if (value.UserStatus == 2) + else if (value.UserStatus == UserStates.ChangePassword) ret = BootstrapUser.ChangePassword(value.UserName, value.Password, value.NewPassword); } return ret; @@ -82,6 +83,7 @@ namespace Bootstrap.Admin.Controllers.Api { value.Description = string.Format("管理员{0}创建用户", User.Identity.Name); value.ApprovedBy = User.Identity.Name; + value.ApprovedTime = DateTime.Now; return UserHelper.SaveUser(value); } /// @@ -104,20 +106,6 @@ namespace Bootstrap.Admin.Controllers.Api case "group": ret = UserHelper.SaveUsersByGroupId(id, userIds); break; - case "user": - // 此时 userIds 存储的信息是操作结果 1 标示同意 0 标示拒绝 - var user = new User() { Id = id, UserStatus = 2 }; - if (userIds == "1") - { - user.ApprovedBy = User.Identity.Name; - } - else - { - user.RejectedReason = "无原因"; - user.RejectedBy = User.Identity.Name; - } - ret = UserHelper.SaveUser(user); - break; default: break; } diff --git a/Bootstrap.Admin/Controllers/Api/WSController.cs b/Bootstrap.Admin/Controllers/Api/WSController.cs new file mode 100644 index 00000000..a7eb5685 --- /dev/null +++ b/Bootstrap.Admin/Controllers/Api/WSController.cs @@ -0,0 +1,23 @@ +using Bootstrap.DataAccess; +using Microsoft.AspNetCore.Mvc; +using System.Collections.Generic; + +namespace Bootstrap.Admin.Controllers.Api +{ + /// + /// + /// + [Route("api/[controller]")] + public class WSController : Controller + { + /// + /// + /// + /// + [HttpPost] + public IEnumerable Post() + { + return NotificationHelper.RetrieveMessages(); + } + } +} diff --git a/Bootstrap.Admin/Startup.cs b/Bootstrap.Admin/Startup.cs index bf351391..4c8c95a2 100644 --- a/Bootstrap.Admin/Startup.cs +++ b/Bootstrap.Admin/Startup.cs @@ -82,7 +82,7 @@ namespace Bootstrap.Admin app.UseCookiePolicy(); app.UseAuthentication(); app.UseBootstrapRoleAuthorization(); - app.UseWebSocketHandler(options => options.UseAuthentication = true); + app.UseWebSocketHandler(options => options.UseAuthentication = true, WSHelper.WebSocketMessageHandler); app.UseCacheManagerCorsHandler(); app.UseMvc(routes => { diff --git a/Bootstrap.Admin/appsettings.json b/Bootstrap.Admin/appsettings.json index 96aed6ed..212d7d84 100644 --- a/Bootstrap.Admin/appsettings.json +++ b/Bootstrap.Admin/appsettings.json @@ -105,7 +105,7 @@ { "Enabled": true, "Key": "UserHelper-RetrieveNewUsers", - "Interval": 30, + "Interval": 600, "SlidingExpiration": true, "Desc": "新用户数据缓存" }, @@ -220,6 +220,13 @@ "Interval": 21600, "SlidingExpiration": true, "Desc": "Token 数据缓存" + }, + { + "Enabled": true, + "Key": "NotificationHelper-PullNotificationsInterval", + "Interval": 10, + "SlidingExpiration": false, + "Desc": "全局消息提示轮询时间间隔" } ] } diff --git a/Bootstrap.Admin/wwwroot/js/common-scripts.js b/Bootstrap.Admin/wwwroot/js/common-scripts.js index bdc749b8..81b5d303 100644 --- a/Bootstrap.Admin/wwwroot/js/common-scripts.js +++ b/Bootstrap.Admin/wwwroot/js/common-scripts.js @@ -42,28 +42,6 @@ }); return this; }, - pullNotification: function () { - var that = this; - var uri = "ws://" + window.location.host + $.formatUrl("WS"); - var socket = new WebSocket(uri); - socket.onmessage = function (e) { - var result = JSON.parse(e.data); - for (index in result) { - var cate = result[index].Category; - var msg = result[index].Message; - switch (cate) { - case "Notification": - toastr.error(msg, "应用程序出现错误"); - break; - case "Users": - toastr.info(msg, "新用户注册"); - break; - } - } - if (result.length > 0) that.reloadWidget(); - }; - return this; - }, reloadWidget: function () { if (this.length === 0) return this; var that = this; @@ -134,7 +112,7 @@ $(function () { "onclick": null, "showDuration": "600", "hideDuration": "2000", - "timeOut": "5000", + "timeOut": "4000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", @@ -194,5 +172,25 @@ $(function () { $('[data-toggle="dropdown"].dropdown-select').dropdown('select'); // load widget data - $('.header .nav').reloadWidget().pullNotification(); + $('.header .nav').reloadWidget().socketHandler({ + onmessage: function (e) { + var result = JSON.parse(e.data); + for (index in result) { + var cate = result[index].Category; + var msg = result[index].Message; + switch (cate) { + case "Notification": + toastr.error(msg, "应用程序出现错误"); + break; + case "Users": + toastr.success(msg, "新用户注册"); + break; + case "Exception": + toastr.warning(msg, "程序发生异常"); + break; + } + } + if (result.length > 0) this.reloadWidget(); + } + }); }); \ No newline at end of file diff --git a/Bootstrap.Admin/wwwroot/js/longbow.common.js b/Bootstrap.Admin/wwwroot/js/longbow.common.js index 531f67ff..eacc920c 100644 --- a/Bootstrap.Admin/wwwroot/js/longbow.common.js +++ b/Bootstrap.Admin/wwwroot/js/longbow.common.js @@ -225,68 +225,6 @@ window.lgbSwal = $.lgbSwal; - // Roles - Role = { - url: 'api/Roles/', - title: "授权角色" - }; - - // Users - User = { - url: 'api/Users/', - title: "授权用户" - }; - - // Groups - Group = { - url: 'api/Groups/', - title: "授权部门" - }; - - // Menus - Menu = { - url: 'api/Menus/', - iconView: 'Admin/IconView', - title: "授权菜单" - }; - - // Exceptions - Exceptions = { - url: 'api/Exceptions/', - title: "程序异常日志" - }; - - // Dicts - Dicts = { - url: 'api/Dicts/' - }; - - // Profiles - Profiles = { - url: 'api/Profiles/' - }; - - // Settings - Settings = { - url: 'api/Settings/', - title: '网站设置' - }; - - // Messages - Messages = { - url: 'api/Messages/' - }; - - // Tasks - Tasks = { - url: 'api/Tasks/' - }; - - // Notifications - Notifications = { - url: 'api/Notifications/' - }; - $.fn.extend({ fixCollapse: function () { var $root = this; @@ -367,6 +305,77 @@ $('#' + $(this).attr('id').replace('tb_', 'btn_')).trigger("click"); }).insertBefore(this.parents('.bootstrap-table').find('.fixed-table-toolbar > .bs-bars')); return this; + }, + msgHandler: function (options) { + var settings = { + url: 'api/WS/', + interval: 10000, + sendMessage: '', + timerHandler: null, + onopen: function (e) { }, + onmessage: function (e) { }, + onclose: function (e) { }, + errorHandler: function (e) { if (toastr && $.isFunction(toastr.error)) toastr.error("连接服务器失败!", "系统错误"); }, + loop: function () { + var that = this; + var uri = window.location.protocol + "//" + window.location.host + $.formatUrl(settings.url); + $.bc({ + url: uri, + id: this.sendMessage, + swal: false, + toastr: false, + callback: function (result) { + if (!result) { + that.errorHandler.call(that.target); + return; + } + that.onmessage.call(that.target, { data: JSON.stringify(result) }); + } + }); + + if (this.timerHandler !== null) clearTimeout(this.timerHandler); + this.timerHandler = setTimeout(function () { that.loop(); }, that.interval); + } + }; + $.extend(settings, options, { target: this }); + settings.loop(); + return this; + }, + socketHandler: function (options) { + // WebSocket消息处理方法 + var settings = { + url: 'WS', + interval: 30000, + sendMessage: 'keepalive', + timerHandler: null, + onopen: function (e) { }, + onerror: function (e) { }, + errorHandler: function (e) { if (window.toastr && $.isFunction(window.toastr.error)) toastr.error("连接服务器失败!", "系统错误"); }, + onmessage: function (e) { }, + onclose: function (e) { }, + loop: function (socket) { + var that = this; + if (socket.readyState === 1) { + socket.send(this.sendMessage); + if (this.timerHandler !== null) clearTimeout(this.timerHandler); + this.timerHandler = setTimeout(function () { that.loop(socket); }, that.interval); + } + else { + this.errorHandler(); + } + } + }; + $.extend(settings, options, { target: this }); + var uri = "ws://" + window.location.host + $.formatUrl(settings.url); + var socket = new WebSocket(uri); + socket.onopen = function (e) { settings.onopen.call(settings.target, e); settings.loop(socket); }; + socket.onerror = function (e) { + settings.onerror.call(settings.target, e); + settings.target.msgHandler(options); + }; + socket.onmessage = function (e) { settings.onmessage.call(settings.target, e); }; + socket.onclose = function (e) { settings.onclose.call(settings.target, e); }; + return this; } }); @@ -386,4 +395,66 @@ }); } }); + + // Roles + Role = { + url: 'api/Roles/', + title: "授权角色" + }; + + // Users + User = { + url: 'api/Users/', + title: "授权用户" + }; + + // Groups + Group = { + url: 'api/Groups/', + title: "授权部门" + }; + + // Menus + Menu = { + url: 'api/Menus/', + iconView: 'Admin/IconView', + title: "授权菜单" + }; + + // Exceptions + Exceptions = { + url: 'api/Exceptions/', + title: "程序异常日志" + }; + + // Dicts + Dicts = { + url: 'api/Dicts/' + }; + + // Profiles + Profiles = { + url: 'api/Profiles/' + }; + + // Settings + Settings = { + url: 'api/Settings/', + title: '网站设置' + }; + + // Messages + Messages = { + url: 'api/Messages/' + }; + + // Tasks + Tasks = { + url: 'api/Tasks/' + }; + + // Notifications + Notifications = { + url: 'api/Notifications/' + }; })(jQuery); \ No newline at end of file diff --git a/Bootstrap.Admin/wwwroot/js/noti.js b/Bootstrap.Admin/wwwroot/js/noti.js index c481f044..ca71e926 100644 --- a/Bootstrap.Admin/wwwroot/js/noti.js +++ b/Bootstrap.Admin/wwwroot/js/noti.js @@ -12,7 +12,7 @@ { title: "注册时间", field: "RegisterTime" }, { title: "操作", field: "Id", formatter: function (value, row, index, field) { - return $.format(' ', value); + return $.format(' ', value); } } ] @@ -21,10 +21,11 @@ var id = $this.attr('data-id'); var result = $this.attr('data-result'); $.bc({ - id: id, url: User.url, method: "PUT", data: { type: "user", userIds: result }, title: result === "1" ? "授权用户" : "拒绝用户", + id: id, url: 'api/New/', method: "PUT", data: { Id: id, UserStatus: result }, title: result === "ApproveUser" ? "授权用户" : "拒绝用户", callback: function (result) { + if (!result) return; $table.bootstrapTable('refresh'); - $.pullNotification($('.header .nav').reloadWidget()); + $('.header .nav').reloadWidget(); } }); }); diff --git a/Bootstrap.Admin/wwwroot/js/profiles.js b/Bootstrap.Admin/wwwroot/js/profiles.js index 07137661..26cbe95d 100644 --- a/Bootstrap.Admin/wwwroot/js/profiles.js +++ b/Bootstrap.Admin/wwwroot/js/profiles.js @@ -36,11 +36,11 @@ var data = dataBinder.get(); switch ($this.attr('data-method')) { case 'password': - data.UserStatus = 2; + data.UserStatus = 'ChangePassword'; $.bc({ url: User.url, method: "PUT", data: data, title: "更改密码" }); break; case 'user': - data.UserStatus = 1; + data.UserStatus = 'ChangeDisplayName'; $.bc({ url: User.url, method: "PUT", data: data, title: "修改用户显示名称", callback: function (result) { @@ -51,7 +51,7 @@ }); break; case 'css': - data.UserStatus = 3; + data.UserStatus = 'ChangeTheme'; $.bc({ url: User.url, method: "PUT", data: data, title: "保存样式" }); break; } diff --git a/Bootstrap.DataAccess/NotificationHelper.cs b/Bootstrap.DataAccess/NotificationHelper.cs index f97b4359..62e47b0a 100644 --- a/Bootstrap.DataAccess/NotificationHelper.cs +++ b/Bootstrap.DataAccess/NotificationHelper.cs @@ -1,13 +1,9 @@ -using Longbow; -using Longbow.Cache; -using Longbow.Logging; +using Longbow.Cache; +using Longbow.Web.WebSockets; +using Newtonsoft.Json; using System; -using System.Collections.Concurrent; using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Linq; -using System.Threading; +using System.Text; namespace Bootstrap.DataAccess { @@ -20,125 +16,41 @@ namespace Bootstrap.DataAccess /// /// internal const string RetrieveNotificationsDataKey = "NotificationHelper-RetrieveNotifications"; + private const string PullNotificationsIntervalDataKey = "NotificationHelper-PullNotificationsInterval"; + private static readonly List MessagePool = new List(); /// /// /// - public static ConcurrentBag MessagePool { get; } = new ConcurrentBag(); - /// - /// 新用户注册的通知的面板显示 - /// + /// /// - public static IEnumerable RetrieveNotifications() + public static void PushMessage(MessageBody message) { - var notifies = CacheManager.GetOrAdd(RetrieveNotificationsDataKey, key => - { - string sql = "select * from Notifications"; - List notifications = new List(); - DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql); - try - { - using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd)) - { - while (reader.Read()) - { - notifications.Add(new Notification() - { - Id = (int)reader[0], - Category = (string)reader[1], - Title = (string)reader[2], - Content = (string)reader[3], - RegisterTime = (DateTime)reader[4], - ProcessTime = LgbConvert.ReadValue(reader[5], DateTime.MinValue), - ProcessBy = LgbConvert.ReadValue(reader[6], string.Empty), - ProcessResult = LgbConvert.ReadValue(reader[7], string.Empty), - Status = (string)reader[8] - }); - } - } - } - catch (Exception ex) { ExceptionManager.Publish(ex); } - return notifications; + MessagePool.Add(message); + CacheManager.Clear(PullNotificationsIntervalDataKey); - }); - notifies.AsParallel().ForAll(n => - { - var ts = DateTime.Now - n.RegisterTime; - if (ts.TotalMinutes < 5) n.Period = "刚刚"; - else if (ts.Days > 0) n.Period = string.Format("{0}天", ts.Days); - else if (ts.Hours > 0) n.Period = string.Format("{0}小时", ts.Hours); - else if (ts.Minutes > 0) n.Period = string.Format("{0}分钟", ts.Minutes); - }); - return notifies.OrderByDescending(n => n.RegisterTime); - } - /// - /// 点击某一行用户注册通知的处理成功操作 - /// - /// - /// - public static bool ProcessRegisterUser(string id) - { - if (string.IsNullOrEmpty(id)) return false; - bool ret = false; - try - { - using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_ProcessRegisterUser")) - { - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", id)); - DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd); - } - CacheCleanUtility.ClearCache(notifyIds: id); - ret = true; - } - catch (Exception ex) - { - ExceptionManager.Publish(ex); - } - return ret; + // websocket message push + WebSocketServerManager.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new MessageBody[] { message })))); } /// /// /// - /// /// - public static bool SaveNotification(Notification noti) + public static IEnumerable RetrieveMessages() { - if (string.IsNullOrEmpty(noti.Title) || string.IsNullOrEmpty(noti.Content)) return false; - bool ret = false; - try + return CacheManager.GetOrAdd(PullNotificationsIntervalDataKey, key => { - using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, "Insert into Notifications (Category, Title, Content, RegisterTime) values (N'2', @Title, @Content, GetDate())")) - { - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@Title", noti.Title)); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@Content", noti.Content)); - DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd); - } - CacheCleanUtility.ClearCache(notifyIds: string.Empty); - ret = true; - } - catch (Exception ex) - { - ExceptionManager.Publish(ex); - } - return ret; + var msgs = new MessageBody[MessagePool.Count]; + MessagePool.CopyTo(msgs, 0); + MessagePool.Clear(); + return new List(msgs); + }); } } /// /// /// - public class MessageBody : IDisposable + public class MessageBody { - /// - /// - /// - public MessageBody() - { - timer = new Timer(state => - { - var msg = this; - NotificationHelper.MessagePool.TryTake(out msg); - }, null, 5000, Timeout.Infinite); - } - private Timer timer = null; /// /// /// @@ -155,24 +67,5 @@ namespace Bootstrap.DataAccess { return string.Format("{0}-{1}", Category, Message); } - private void Dispose(bool disposing) - { - if (disposing) - { - if (timer != null) - { - timer.Dispose(); - timer = null; - } - } - } - /// - /// - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } } } diff --git a/Bootstrap.DataAccess/User.cs b/Bootstrap.DataAccess/User.cs index 4bcb7ec5..a8ca3be0 100644 --- a/Bootstrap.DataAccess/User.cs +++ b/Bootstrap.DataAccess/User.cs @@ -41,9 +41,9 @@ namespace Bootstrap.DataAccess /// public string Description { get; set; } /// - /// 获得/设置 用户当前状态 0 表示管理员注册用户 1 表示用户自己注册 2 表示管理员批复 3 表示更改个人皮肤 9 表示前台remote validate + /// 获得/设置 用户当前状态 0 表示管理员注册用户 1 表示用户注册 2 表示更改密码 3 表示更改个人皮肤 4 表示更改显示名称 5 批复新用户注册操作 /// - public int UserStatus { get; set; } + public UserStates UserStatus { get; set; } /// /// 获得/设置 通知描述 2分钟内为刚刚 /// @@ -73,4 +73,30 @@ namespace Bootstrap.DataAccess return string.Format("{0} ({1})", UserName, DisplayName); } } + /// + /// + /// + public enum UserStates + { + /// + /// + /// + ChangePassword, + /// + /// + /// + ChangeTheme, + /// + /// + /// + ChangeDisplayName, + /// + /// + /// + ApproveUser, + /// + /// + /// + RejectUser + } } diff --git a/Bootstrap.DataAccess/UserHelper.cs b/Bootstrap.DataAccess/UserHelper.cs index d11cee38..c39c7b2d 100644 --- a/Bootstrap.DataAccess/UserHelper.cs +++ b/Bootstrap.DataAccess/UserHelper.cs @@ -2,7 +2,6 @@ using Longbow; using Longbow.Cache; using Longbow.Data; -using Longbow.Logging; using Longbow.Security; using System; using System.Collections.Generic; @@ -106,30 +105,63 @@ namespace Bootstrap.DataAccess public static bool SaveUser(User p) { if (p.Id == 0 && p.Description.Length > 500) p.Description = p.Description.Substring(0, 500); - if (p.UserStatus != 2) - { - if (p.UserName.Length > 50) p.UserName = p.UserName.Substring(0, 50); - p.PassSalt = LgbCryptography.GenerateSalt(); - p.Password = LgbCryptography.ComputeHash(p.Password, p.PassSalt); - } - bool ret = false; + if (p.UserName.Length > 50) p.UserName = p.UserName.Substring(0, 50); + p.PassSalt = LgbCryptography.GenerateSalt(); + p.Password = LgbCryptography.ComputeHash(p.Password, p.PassSalt); using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_SaveUsers")) { - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", p.Id)); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@userName", DBAccessFactory.ToDBValue(p.UserName))); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@password", DBAccessFactory.ToDBValue(p.Password))); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@passSalt", DBAccessFactory.ToDBValue(p.PassSalt))); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@displayName", DBAccessFactory.ToDBValue(p.DisplayName))); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@description", DBAccessFactory.ToDBValue(p.Description))); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@userName", p.UserName)); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@password", p.Password)); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@passSalt", p.PassSalt)); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@displayName", p.DisplayName)); cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@approvedBy", DBAccessFactory.ToDBValue(p.ApprovedBy))); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedBy", DBAccessFactory.ToDBValue(p.RejectedBy))); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedReason", DBAccessFactory.ToDBValue(p.RejectedReason))); - cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@userStatus", p.UserStatus)); + object approvedTime = p.ApprovedTime; + if (p.ApprovedTime == DateTime.MinValue) approvedTime = DBNull.Value; + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@approvedTime", approvedTime)); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@description", p.Description)); DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd); } CacheCleanUtility.ClearCache(userIds: p.Id == 0 ? string.Empty : p.Id.ToString()); - ret = true; - if (p.UserStatus == 1) NotificationHelper.MessagePool.Add(new MessageBody() { Category = "Users", Message = string.Format("{0}-{1}", p.UserName, p.Description) }); + return true; + } + /// + /// + /// + /// + /// + /// + public static bool ApproveUser(int id, string approvedBy) + { + var ret = false; + var sql = "update Users set ApprovedTime = GETDATE(), ApprovedBy = @approvedBy where ID = @id"; + using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", id)); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@approvedBy", approvedBy)); + ret = DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheCleanUtility.ClearCache(userIds: id.ToString()); + return ret; + } + /// + /// + /// + /// + /// + /// + /// + public static bool RejectUser(int id, string rejectBy) + { + var ret = false; + var sql = "update Users set RejectedTime = GETDATE(), RejectedBy = @rejectedBy, RejectedReason = @rejectedReason where ID = @id"; + using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql)) + { + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@id", id)); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedBy", rejectBy)); + cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@rejectedReason", "未填写")); + ret = DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd) == 1; + } + CacheCleanUtility.ClearCache(userIds: id.ToString()); return ret; } /// diff --git a/Bootstrap.DataAccess/WSHelper.cs b/Bootstrap.DataAccess/WSHelper.cs new file mode 100644 index 00000000..065e9f83 --- /dev/null +++ b/Bootstrap.DataAccess/WSHelper.cs @@ -0,0 +1,19 @@ +namespace Bootstrap.DataAccess +{ + /// + /// + /// + public static class WSHelper + { + /// + /// + /// + /// + /// + public static byte[] WebSocketMessageHandler(byte[] data) + { + return null; + } + } +} + diff --git a/DatabaseScripts/Procedures.sql b/DatabaseScripts/Procedures.sql index cc2e6eb2..008c3f47 100644 --- a/DatabaseScripts/Procedures.sql +++ b/DatabaseScripts/Procedures.sql @@ -174,16 +174,13 @@ GO -- ============================================= CREATE PROCEDURE [dbo].[Proc_SaveUsers] -- Add the parameters for the stored procedure here - @id int, @userName varchar(50), @password varchar(50), @passSalt varchar(50), @displayName nvarchar(50), - @approvedBy varchar(50) = null, - @description nvarchar(500), - @rejectedBy varchar(50) = null, - @rejectedReason nvarchar(500) = null, - @userStatus int = 0 --0表示管理员创建 1标示用户注册 2标示管理员批复 + @approvedBy nvarchar(50), + @approvedTime datetime, + @description nvarchar(500) WITH ENCRYPTION AS BEGIN @@ -192,50 +189,12 @@ BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; -- Insert statements for procedure here - if @userStatus = 2 + begin + if(not exists (select 1 from Users Where UserName = @userName)) begin - if @approvedBy is not null - update Users set ApprovedTime = GETDATE(), ApprovedBy = @approvedBy where ID = @id - else - update Users set RejectedTime = GETDATE(), RejectedBy = @rejectedBy, RejectedReason = @rejectedReason where ID = @id - end - else - begin - declare @approveTime datetime = null - if @userStatus = 0 set @approveTime = GETDATE() - if(@id = 0 and not exists (select 1 from Users Where UserName = @userName)) - begin - Insert Into Users (UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedTime, [Description]) values (@userName, @password, @passSalt, @displayName, GETDATE(), @approveTime, @description) - insert into UserRole (UserID, RoleID) select @@IDENTITY, ID from Roles where RoleName = N'Default' - end - else - Update Users set [Password] = @password, PassSalt = @passSalt, DisplayName = @displayName where ID = @id + Insert Into Users (UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedBy, ApprovedTime, [Description]) values (@userName, @password, @passSalt, @displayName, GETDATE(), @approvedBy, @approvedTime, @description) + insert into UserRole (UserID, RoleID) select @@IDENTITY, ID from Roles where RoleName = N'Default' end + end END GO - -Drop PROCEDURE Proc_ProcessRegisterUser -GO --- ============================================= --- Author: XiaTiantian --- Create date: 2016-11-10 --- Description: --- ============================================= -Create PROCEDURE Proc_ProcessRegisterUser - -- Add the parameters for the stored procedure here - @id int - WITH ENCRYPTION -AS -BEGIN - -- SET NOCOUNT ON added to prevent extra result sets from - -- interfering with SELECT statements. - SET NOCOUNT ON; - SET XACT_ABORT ON; - -- Insert statements for procedure here - update Users set ApprovedTime=GETDATE() where UserName=(select Title from Notifications where ID=@id) - update Notifications set Status='1',ProcessTime=GETDATE(),ProcessResult='0' where ID=@id -END -GO - - -