/// <summary> /// Get a user Principal with claims added /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <param name="getClaims"></param> internal static async Task <ClaimsPrincipal> GetPrincipalAsync(AuthUserModel user, string password, GetClaims?getClaims) { // Create claims object var claims = new List <Claim> { new (JwtClaimTypes.UserId, user.Id.Value.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer32), new (ClaimTypes.Name, user.FriendlyName ?? user.EmailAddress, ClaimValueTypes.String), new (ClaimTypes.Email, user.EmailAddress, ClaimValueTypes.Email), }; // Add super permission if (user.IsSuper) { claims.Add(new(JwtClaimTypes.IsSuper, true.ToString(), ClaimValueTypes.Boolean)); } // Add roles foreach (var role in user.Roles) { claims.Add(new(ClaimTypes.Role, role.Name, ClaimValueTypes.String)); } // Add custom Claims if (getClaims != null) { claims.AddRange(await getClaims(user, password).ConfigureAwait(false)); } // Create and return identity and principal objects var userIdentity = new ClaimsIdentity(claims, "SecureSignIn"); return(new ClaimsPrincipal(userIdentity)); }
public void BindBasisInfo(RoleEntity roleEntity, AuthUserModel authUserModel) { roleEntity.Creator = authUserModel.UserSysNo; roleEntity.CreateTime = DateTime.Now; roleEntity.Updater = authUserModel.UserSysNo; roleEntity.UpdateTime = DateTime.Now; }
private AuthUserModel BuildAuthUserModel(ApplicationUser model) { AuthUserModel authUserModel = new AuthUserModel(); authUserModel.User = model; if (authUserModel.User.Is_validated) { authUserModel.IsAuthenticated = true; //if (authUserModel.User.Pstatus == "Y") if (authUserModel.User.Pstatus == "Y" && !string.IsNullOrEmpty(authUserModel.User.EmailId) && !string.IsNullOrEmpty(authUserModel.User.EmployeeId)) { authUserModel.FeatureList = featureService.GetAuthFeatureList(authUserModel.User.Id); } else { authUserModel.FeatureList = new List <dynamic>(); } authUserModel.BearerToken = Guid.NewGuid().ToString(); } else { authUserModel.IsAuthenticated = false; } return(authUserModel); }
public Task Invoke(HttpContext httpContext) { try { string authToken = httpContext.Request.Headers["Authorization"]; if (authToken != null) { JwtSecurityToken token = new JwtSecurityTokenHandler().ReadJwtToken(authToken.Split(' ')[1]); // Parse out authuser model AuthUserModel model = new AuthUserModel { Id = int.Parse(token.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).FirstOrDefault()?.Value), Email = token.Claims.Where(c => c.Type == ClaimTypes.Email).FirstOrDefault().Value, Username = token.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value, IsModerator = bool.Parse(token.Claims.Where(c => c.Type == ClaimTypes.Role).FirstOrDefault()?.Value) }; httpContext.Items["authUserModel"] = model; } return(_next(httpContext)); } catch { return(_next(httpContext)); } }
private string CreateJwtToken(AuthUserModel authModel) { try { JwtSettings settings = new JwtSettings(); jwtModel = settings.Initiate(); SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtModel.Key)); List <Claim> jwtClaims = new List <Claim>(); jwtClaims.Add(new Claim(JwtRegisteredClaimNames.Sub, authModel.User.Username.ToString())); jwtClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); jwtClaims.Add(new Claim("IsAuthenticated", authModel.IsAuthenticated.ToString().ToLower())); var token = new JwtSecurityToken(jwtModel.Issuer, jwtModel.Audience, jwtClaims, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(jwtModel.MinutesToExpiration), new SigningCredentials(key, SecurityAlgorithms.HmacSha256)); return(new JwtSecurityTokenHandler().WriteToken(token)); } catch (Exception ex) { return(errorLogService.InsertToErrorLog(ex, MethodBase.GetCurrentMethod().Name, Request.Headers["UserInfo"].ToString()).ToString()); } }
public IActionResult Authenticate([FromBody] AuthUserModel model) { var user = _userService.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect." })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info and authentication token return(Ok(new { Id = user.Id, Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, GradeLevel = user.GradeLevel, Course = user.Course, Token = tokenString })); }
public object Login([FromBody] LoginModel model) { try { AuthUserModel obj = usersService.login(model); if (obj.IsAuthenticated && obj.User.LogInStatus == "N") { obj.IsAuthenticated = false; } if (obj.IsAuthenticated && obj.User.Pstatus == "L") { obj.IsAuthenticated = false; } if (obj.IsAuthenticated) { obj.BearerToken = CreateJwtToken(obj); return(StatusCode(StatusCodes.Status200OK, obj)); } else { return(StatusCode(StatusCodes.Status200OK, obj)); } } catch (Exception ex) { errorLogService.InsertToErrorLog(ex, MethodBase.GetCurrentMethod().Name, Request.Headers["UserInfo"].ToString()); return(StatusCode(StatusCodes.Status401Unauthorized));; } }
private async Task <AuthUserModel> SetAuthState(AuthUserModel result) { lock (_state) { _state.User = new UserModel { Id = result.Id, FirstName = result.FirstName, LastName = result.LastName, Email = result.Email, Grade = result.Grade, Admin = result.Admin, Instructor = result.Instructor }; } await _localStorage.SetItemAsync("userId", result.Id); await _localStorage.SetItemAsync("authToken", result.Token); await _localStorage.SetItemAsync("authTokenExpiry", result.Expiry); ((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsAuthenticated(result.Token); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.Token); return(result); }
/// <summary> /// Hides a comment if the user is a moderator /// </summary> /// <param name="authUser">The user making the request</param> /// <param name="commentId">The comment that is being hidden</param> /// <param name="hideComment">If we are hiding the comment</param> /// <returns> /// A updated comment model /// </returns> public CommentModel HideComment(AuthUserModel authUser, int commentId, bool hideComment) { // Validate user is moderator bool isModerator = context.Users .Where(u => u.Id == authUser.Id) .Select(u => u.IsModerator) .FirstOrDefault(); if (!isModerator) { throw new Exception("Not a moderator"); } IQueryable <Comment> commentQuery = context.Comments .Where(c => c.Id == commentId); Comment comment = commentQuery .FirstOrDefault(); comment.IsHidden = hideComment; context.SaveChanges(); return(this.CommentModelQuery(commentQuery, authUser.Id) .FirstOrDefault()); }
public bool UnsubscribeUser(string email) { if (string.IsNullOrWhiteSpace(email)) { return(false); } email = email.Trim(); AuthUserModel user = this.authStorage.GetUser(email); if (user == null) { return(false); } this.userDinnerStorage.SetUserSettings( new UserSettingsModel { SendAdminNotification = false, SendChangedOrderNotification = false, SendWeeklyNotification = false, SendDailyNotification = false }, user.ID); return(true); }
/// <summary> /// 登录 /// </summary> /// <typeparam name="T">登录信息类</typeparam> /// <param name="loginModel">登录信息</param> /// <returns></returns> public AuthUserModel LoginV2 <T>(T loginModel) where T : LoginModel { UserEntity userEntity = UserService.GetByLoginNameAndPassword(loginModel.Account, loginModel.Password); if (userEntity == null) { throw new BusinessException(LangHelper.GetText("用户或者密码错误!", "PortalBase.DBAuth")); } if (userEntity.CommonStatus == CommonStatus.DeActived) { throw new BusinessException("该登录用户已被禁用,请联系管理员"); } AuthUserModel authUser = new AuthUserModel() { UserSysNo = userEntity.Id, UserDisplayName = userEntity.UserFullName, UserID = userEntity.LoginName, UsrCommonStatus = (AuthUserStatus)((int)userEntity.CommonStatus) };//todo 登陆实现 if (authUser != null && authUser.UserSysNo > 0) { //清除本机缓存 RsetUserLocalCache(authUser); } return(authUser); }
public bool HasAuth(string authKey, AuthUserModel user) { var result = GetUserMenuList(user); var permissionList = result.Permissions; return(permissionList.Exists(p => p.PermissionKey.ToLower().Trim() == authKey.ToLower().Trim())); }
public AuthUserDataModel GetUserMenuList(AuthUserModel user) { if (user == null || user.UserSysNo <= 0) { AuthUserDataModel result = new AuthUserDataModel(); result.Menus = new List <AuthMenuModel>(); result.Permissions = new List <AuthPermissionModel>(); result.Roles = new List <AuthRoleModel>(); return(result); } string keyWithoutLoginTime = CacheManager.GenerateKey(CACHE_KEY_USER_MENU, this.ApplicationKey, user.UserID); string keyWithLoginTime = CacheManager.GenerateKey(keyWithoutLoginTime, user.UILoginTime); return(CacheManager.GetWithCache <AuthUserDataModel>(keyWithLoginTime, () => { //移除失效的缓存 CacheManager.RemoveStartsWith(keyWithoutLoginTime + "_"); BlueStone.Smoke.Entity.CurrentUser cUser = new Entity.CurrentUser() { UserSysNo = user.UserSysNo, LoginTime = user.UILoginTime, UserName = user.UserID }; return authService.GetUserMenuList(cUser, AuthMgr.GetApplicationKey()); //return Rpc.Call<AuthUserDataModel>("AuthService.AuthService.GetUserMenuList", user.UserSysNo, AuthMgr.GetApplicationKey()); }, 60 * 60 * 8)); }
public ActionResult SignUp(AuthUserModel signupUser) { User user; using (var cx = new ViralContext()) { if (cx.Users.Any(u => u.Username == signupUser.Username)) { return(View("PartialSignup", signupUser)); } user = cx.Users.Add(new User { Username = signupUser.Username, Password = signupUser.Password, Email = signupUser.Email, AvatarPath = signupUser.AvatarPath, RegisteredTime = DateTime.UtcNow }); cx.SaveChanges(); } FormsAuthentication.SetAuthCookie(user.Id.ToString(), true); return(RedirectToAction("Index", "Home", user)); }
public void ClearCachedData(AuthUserModel user) { string keyWithoutLoginTime = CacheManager.GenerateKey(CACHE_KEY_USER_MENU, this.ApplicationKey, user.UserID); CacheManager.RemoveStartsWith(keyWithoutLoginTime + "_"); authService.ClearAuthData(user.UserID, AuthMgr.GetApplicationKey()); //Rpc.Call<AuthUserModel>("AuthService.AuthService.ClearAuthData"); }
private bool Authenticate(AuthUserModel authUser, out User user) { using (var cx = new ViralContext()) { user = cx.Users.SingleOrDefault(u => authUser.Username.Equals(u.Username, StringComparison.OrdinalIgnoreCase) && u.Password == authUser.Password); return(user != null); } }
public async Task <IActionResult> Auth([FromBody] AuthUserModel authUser) { var authToken = await _authUserService.AuthenticateUserAsync(authUser.UserName, authUser.Password); return(authToken == null ? StatusCode(StatusCodes.Status401Unauthorized, null) : StatusCode(StatusCodes.Status200OK, authToken)); }
public List <AuthPermissionModel> LoadAllPermissions(AuthUserModel user) { string keyWithoutLoginTime = CacheManager.GenerateKey(CACHE_KEY_ALL_PERMISSION, this.ApplicationKey); return(CacheManager.GetWithCache <List <AuthPermissionModel> >(keyWithoutLoginTime, () => { return authService.LoadAllPermissions(this.ApplicationKey); //return Rpc.Call<List<AuthPermissionModel>>("AuthService.AuthService.LoadAllPermissions", this.ApplicationKey); }, 60 * 60 * 8)); }
/// <summary> /// Generates an account history of posts and comments /// </summary> /// <param name="authUser">The authorized user to get the history for</param> /// <param name="page">The page number of viewing</param> /// <returns> /// A list of history items /// </returns> public HistoryModel History(AuthUserModel authUser, int page) { // Get a query of the ids in order and the types var historyIds = context.Posts .Where(p => p.Posted_ById == authUser.Id) .Select(p => new { Id = p.Id, Created = p.Posted_At, Post = true, Comment = false }) .Union( context.Comments .Where(com => com.Commented_ById == authUser.Id) .Select(com => new { Id = com.Id, Created = com.Commented_At, Post = false, Comment = true }) ) .OrderByDescending(item => item.Created) .Skip((page - 1) * 25) .Take(25) .ToList(); // Get the comment ids we need to convert to models List <int> commentIds = historyIds.Where(h => h.Comment).Select(h => h.Id).ToList(); // Setup the query to get the comments IQueryable <Comment> commentQuery = context.Comments .Where(com => commentIds.Contains(com.Id)); // Get the comments List <CommentModel> comments = commentService.GetCommentModels(commentQuery, authUser.Id); // Get the post ids we need to convert to models List <int> postIds = historyIds.Where(h => h.Post).Select(h => h.Id).ToList(); // Setup the query to get the comments IQueryable <Post> postQuery = context.Posts .Where(p => postIds.Contains(p.Id)); // Get the posts List <PostListModel> posts = postService.GetPostListModels(postQuery, authUser.Id); // Setup the results return(new HistoryModel { Posts = posts, Comments = comments }); }
public RatingModel GetCommentRating(AuthUserModel authUer, int commentId) { return(context.Ratings .Where(r => r.Comment_Id == commentId && r.User_Id == authUer.Id) .Select(r => new RatingModel { Id = r.Id, Comment_Id = commentId, isUpvote = r.IsUpvoted }) .FirstOrDefault()); }
/// <summary> /// 更新本地用户缓存 /// </summary> /// <param name="user"></param> private void RsetUserLocalCache(AuthUserModel user) { var cacheKey = CacheManager.GenerateKey(Key_Service_User_Auth_Data, user.UserSysNo.ToString()); CacheManager.Remove(cacheKey); //重新加入缓存 CacheManager.GetWithCache(cacheKey, () => { return(user); }, USER_LOCAL_CACHE_SEC); }
/// <summary> /// 登录 /// </summary> /// <param name="userID"></param> /// <param name="pwd"></param> /// <param name="applicationKey"></param> /// <returns></returns> public static AuthUserModel Login(string userID, string pwd, string applicationKey) { DataCommand cmd = new DataCommand("SystemUser_Login"); cmd.SetParameter("@UserID", DbType.String, userID); cmd.SetParameter("@Pwd", DbType.String, pwd); cmd.SetParameter("@ApplicationID", DbType.String, applicationKey); AuthUserModel result = cmd.ExecuteEntity <AuthUserModel>(); return(result); }
/// <inheritdoc /> public DinnerPrincipal GetPrincipal(int?userId) { AuthUserModel userModel = null; if (userId.HasValue) { userModel = this.authStorage.GetUser(userId.Value); } return(new DinnerPrincipal(userModel ?? new UnauthorizeUserModel())); }
/// <summary> /// 更新数据 /// </summary> /// <param name="role">数据实体</param> public void Update(RoleEntity role, AuthUserModel authUserModel) { if (!role.BusinessId.HasValue) { throw new BusinessException("角色Id不允许为空"); } role.Id = role.BusinessId.Value; this.CheckEntity(role); this.BindBasisInfo(role, authUserModel); RoleDA.Update(role); }
/// <summary> /// Notifies the application of the login event /// swapping any views to the authorized view /// </summary> /// <param name="authUser">The current authorized user</param> /// <returns> /// A task of notifying /// </returns> public async Task NotifyUserLogin(AuthUserModel authUser) { await LocalStorage.SetItemAsync <string>("authToken", authUser.Token); await LocalStorage.SetItemAsync <string>("user", authUser.Username); await LocalStorage.SetItemAsync <bool>("moderator", authUser.IsModerator); AuthenticationState authState = await GetAuthenticationStateAsync(); NotifyAuthenticationStateChanged(Task.FromResult(authState)); }
/// <summary> /// Creates a comment from a comment model /// </summary> /// <param name="comment">The comment to create</param> /// <returns> /// The newly created comment model /// </returns> public CommentModel CreateComment(AuthUserModel authUser, CommentModel comment) { // TODO: Verify information Comment commentDB = new Comment { Body = comment.Body, Commented_ById = authUser.Id, Commented_At = DateTime.Now, Commented_UnderId = comment.Parent_Id, Commented_OnId = comment.Post_Id, }; var postInformation = context.Posts .Where(p => p.Id == comment.Post_Id) .Select(p => new { p.Title, p.Posted_ById }) .FirstOrDefault(); context.Comments.Add(commentDB); context.SaveChanges(); CommentModel commentModel = this.CommentModelQuery(context.Comments.Where(com => com.Id == commentDB.Id), null) .FirstOrDefault(); // If this was a post level comment, notify the poster if (commentDB.Commented_UnderId == null && postInformation.Posted_ById != authUser.Id) { messageService.CreateMessage(new AuthMessageModel { Comment = commentModel, Title = "post reply" }, postInformation.Posted_ById); } // If this is under a comment and the current commentor is not the user notify the user if (commentDB.Commented_UnderId != null) { int?commentorId = context.Comments .Where(c => c.Id == commentDB.Commented_UnderId) .Select(c => c.Commented_ById) .FirstOrDefault(); if (commentorId.HasValue && commentorId != authUser.Id) { messageService.CreateMessage(new AuthMessageModel { Comment = commentModel, Title = "comment reply" }, commentorId.Value); } } return(commentModel); }
public async Task <IActionResult> Put([FromServices] OpenLibraryService openLibraryService, [FromServices] IPostService postService, [FromBody] PostModel postModel) { try { AuthUserModel authUser = (AuthUserModel)this.HttpContext.Items["authUserModel"]; var post = await postService.CreatePost(authUser, postModel, openLibraryService); return(Ok(post)); } catch (ArgumentException e) { return(BadRequest(new { ISBN = e.Message })); } }
public List <AuthMessageModel> GetMessages(AuthUserModel authUser, int page) { int?authUserId = authUser?.Id; List <AuthMessageModel> messages = context.Messages .Where(m => m.ForUser_Id == authUser.Id) .Skip((page - 1) * 25) .Take(25) .Select(m => new AuthMessageModel { Id = m.Id, Title = m.Title, Seen = m.Seen, Post = new PostListModel { Title = m.AboutComment.Commented_On.Title }, Comment = new CommentModel { Body = m.AboutComment.Body, Commented_At = m.AboutComment.Commented_At, Commented_By = m.AboutComment.Commented_By.Username, Id = m.AboutComment.Id, Rating = authUserId == null ? null : m.AboutComment.Ratings.Where(r => r.User_Id == authUserId).Select(r => new RatingModel { Id = r.Id, Post_Id = r.Post_Id, isUpvote = r.IsUpvoted }).FirstOrDefault(), PostTitle = m.AboutComment.Commented_On.Title, Post_Id = m.AboutComment.Commented_On.Id, } }) .ToList(); List <int> unreadIds = messages .Where(me => !me.Seen) .Select(me => me.Id) .ToList(); if (unreadIds.Count() > 0) { List <Message> messagesDb = context.Messages .Where(m => unreadIds.Contains(m.Id)) .ToList(); messagesDb.ForEach(m => m.Seen = true); context.SaveChanges(); } return(messages); }
public RatingModel RatingPatch(AuthUserModel authUser, RatingModel ratingModel) { Rating rating = context.Ratings .Where(r => r.Id == ratingModel.Id && authUser.Id == r.User_Id) .FirstOrDefault(); if (rating == null) { throw new Exception("No rating to patch"); } rating.IsUpvoted = ratingModel.isUpvote; context.SaveChanges(); return(ratingModel); }
public ActionResult Login(AuthUserModel authUser, string returnUrl) { if (Authenticate(authUser, out var user)) { FormsAuthentication.SetAuthCookie(user.Id.ToString(), true); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } return(RedirectToAction("Index", "Home", user)); } return(RedirectToAction("Index", "Home", user)); }