public async Task <ActionResult> Register(RegisterModel model) { if (ModelState.IsValid) { UserIdentityDTO userDto = new UserIdentityDTO { Email = model.Email, Password = model.Password, Address = model.Address, Name = model.Name, Role = new RoleDTO { Name = "user" } }; //TODO MAPPER HERE OperationDetails operationDetails = await UserService.Create(userDto); if (operationDetails.Succedeed) { ClaimsIdentity claim = await UserService.Authenticate(userDto); AuthenticationManager.SignOut(); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claim); _evaluateService.AddUser(claim.GetUserId(), userDto.Name, userDto.Email); return(View("SuccessRegister")); } ModelState.AddModelError(operationDetails.Property, operationDetails.Message); } return(View(model)); }
public async Task <IActionResult> PostAsync([FromBody] UserLoginDTO value) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var user = await userManager.FindByEmailAsync(value.Email); if (user == null) { return(Unauthorized()); } if (await userManager.CheckPasswordAsync(user, value.Password)) { var userDto = new UserIdentityDTO() { Email = user.Email, LastName = user.LastName, FirstName = user.FirstName, Id = user.Id, Role = user.Role.Name, EmailConfirmed = user.EmailConfirmed, Blocked = user.Blocked, Password = user.Password }; string jwt = JwtManager.GenerateToken(userDto); return(new JsonResult(jwt)); } return(Unauthorized()); }
public IEnumerable <UserIdentityDTO> GetUsersNotInGroup(int groupId) { var group = db.Groups.Get(groupId); if (group == null) { return(null); } var usersNotInGroup = db.Users.GetUsersNotInGroup(groupId); if (usersNotInGroup == null) { return(null); } var usersNotInGroupList = new List <UserIdentityDTO>(); foreach (var user in usersNotInGroup) { var rdDto = new UserIdentityDTO(user.Email, null, user.Id, user.FirstName, user.LastName, user.Roles.Name, user.Blocked); if (!usersNotInGroupList.Contains(rdDto)) { usersNotInGroupList.Add(rdDto); } } return(usersNotInGroupList); }
public async Task <ActionResult> Login(LoginModel model) { if (ModelState.IsValid) { UserIdentityDTO userDto = new UserIdentityDTO { Email = model.Email, Password = model.Password }; ClaimsIdentity claim = await UserService.Authenticate(userDto); if (claim == null) { ModelState.AddModelError("", "Incorrect login or password."); } else { AuthenticationManager.SignOut(); AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claim); return(RedirectToAction("Index", "Home")); } } return(View(model)); }
public async Task <ActionResult> ConfirmEmailAsync(string token) { try { if (JwtManager.ValidateToken(token, out string userEmail, out string userrole)) { UserIdentityDTO user = await userService.GetByEmailAsync(userEmail); if (user == null) { return(BadRequest("User not found")); } if (await userService.ConfirmEmailByIdAsync(user.Id)) { User confirm_user = await userManager.FindByEmailAsync(userEmail); var token_result = await userManager.GenerateEmailConfirmationTokenAsync(confirm_user); var result = await userManager.ConfirmEmailAsync(confirm_user, token_result); return(Ok("Email confirmed")); } return(BadRequest("Confirmation error")); } return(BadRequest("Token no longer valid")); } catch (Exception e) { return(StatusCode(500)); } }
protected Task <IPrincipal> AuthenticateJwtToken(string token) { string email; string userrole; if (ValidateToken(token, out email, out userrole)) { UserIdentityDTO userDTO = userService.GetByEmail(email); // based on username to get more information from database in order to build local identity var claims = new List <Claim> { new Claim(ClaimTypes.Role, userrole), new Claim("Id", userDTO.Id.ToString()), new Claim(ClaimTypes.Name, userDTO.FirstName) // todo: Add more claims if needed: Roles, ... }; var identity = new ClaimsIdentity(claims, "Jwt"); IPrincipal user = new ClaimsPrincipal(identity); return(Task.FromResult(user)); } return(Task.FromResult <IPrincipal>(null)); }
public UserIdentityDTO CreateUser(UserRegistrationDTO user) { if (Repository.Get(u => u.UserName == user.UserName).Any()) { return(null); } string passwordHash = CalculateMD5Hash(user.Password); Repository.Add(new User { FirstName = user.FirstName, LastName = user.LastName, Role = "user", UserName = user.UserName, HashedPassword = passwordHash }); _unitOfWork.SaveChanges(); User savedUser = Repository.Get(u => u.UserName == user.UserName).FirstOrDefault(); if (savedUser == null) { return(null); } UserIdentityDTO identityDTO = new UserIdentityDTO(); GetUserToUserIdentityDTOMapper().Map(savedUser, identityDTO); return(identityDTO); }
public async Task <IEnumerable <UserIdentityDTO> > GetUsersNotInGroupAsync(int groupId) { Group group = await db.Groups.GetAsync(groupId); if (group == null) { return(null); } var usersNotInGroup = await db.Users.GetUsersNotInGroupAsync(groupId); if (usersNotInGroup == null) { return(null); } var usersNotInGroupList = new List <UserIdentityDTO>(); foreach (var user in usersNotInGroup) { var rdDto = new UserIdentityDTO(user.Email, null, user.Id, user.FirstName, user.LastName, user.Role.Name, user.Blocked, user.EmailConfirmed); if (!usersNotInGroupList.Contains(rdDto)) { usersNotInGroupList.Add(rdDto); } } return(usersNotInGroupList); }
public async Task <OperationDetails> Create(UserIdentityDTO userDto) { ApplicationUser user = await Database.UserManager.FindByEmailAsync(userDto.Email); if (user == null) { user = new ApplicationUser { Email = userDto.Email, UserName = userDto.Email }; var result = await Database.UserManager.CreateAsync(user, userDto.Password); if (result.Errors.Count() > 0) { return(new OperationDetails(false, result.Errors.FirstOrDefault(), "")); } // добавляем роль await Database.UserManager.AddToRoleAsync(user.Id, userDto.Role.Name); // создаем профиль клиента ClientProfile clientProfile = new ClientProfile { Id = user.Id, Address = userDto.Address, Name = userDto.Name }; Database.ClientManager.Create(clientProfile); await Database.SaveAsync(); return(new OperationDetails(true, "Регистрация успешно пройдена", "")); } return(new OperationDetails(false, "Пользователь с таким логином уже существует", "Email")); }
public static string GenerateToken(UserIdentityDTO user, int expireDays = 1, int expireHours = 0) { var symmetricKey = Convert.FromBase64String(Secret); var tokenHandler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim("Id", user.Id.ToString()), new Claim("EmailConfirmed", user.EmailConfirmed.ToString()), new Claim(ClaimTypes.Email, user.Email), new Claim(ClaimTypes.Name, user.FirstName + " " + user.LastName), new Claim(ClaimTypes.Role, user.Role) }), Expires = now.AddDays(expireDays).AddHours(expireHours), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.HmacSha256Signature) }; var stoken = tokenHandler.CreateToken(tokenDescriptor); var token = tokenHandler.WriteToken(stoken); return(token); }
public async Task <int> UpdateAsync(UserIdentityDTO entity) { var user = await genericRepository.GetUserAsync <UserIdentity>(entity.Id); user.FirstName = entity.FirstName; user.LastName = entity.LastName; return(await genericRepository.UpdateAsync(user)); }
public bool CheckUser(string email, string password, out UserIdentityDTO user) { user = userService.GetByEmail(email); if (user == null || user.Blocked == true) { return(false); } var result = BCrypt.Net.BCrypt.Verify(password, user.Password); return(result); }
public async Task <UserIdentityDTO> Assign(UserIdentityDTO user) { var dbuser = Database.UserManager.Users.First(x => x.Id == user.IdentityId); dbuser.Roles.Clear(); dbuser.Roles.Add(new IdentityUserRole { RoleId = user.Role.Id }); await Database.SaveAsync(); return(Mapper.Map(dbuser, Database.RoleManager.Roles.ToList())); }
public async Task <ClaimsIdentity> Authenticate(UserIdentityDTO userDto) { ClaimsIdentity claim = null; // находим пользователя ApplicationUser user = await Database.UserManager.FindAsync(userDto.Email, userDto.Password); // авторизуем его и возвращаем объект ClaimsIdentity if (user != null) { claim = await Database.UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie); } return(claim); }
public UserIdentityDTO GetUserIdentity(string username) { User user = Repository.Get(u => u.UserName == username) .FirstOrDefault(); if (user == null) { return(null); } UserIdentityDTO identityDTO = new UserIdentityDTO(); GetUserToUserIdentityDTOMapper().Map(user, identityDTO); return(identityDTO); }
// начальная инициализация бд public async Task SetInitialData(UserIdentityDTO adminDto, List <string> roles) { foreach (string roleName in roles) { var role = await Database.RoleManager.FindByNameAsync(roleName); if (role == null) { role = new ApplicationRole { Name = roleName }; await Database.RoleManager.CreateAsync(role); } } await Create(adminDto); }
private ClaimsIdentity GetClaimsIdentity(UserIdentityDTO user) { var claims = new List <Claim> { // It's not very nice to have this much, but it would be convenient on frontend)) new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserName), new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role), new Claim("Id", user.Id.ToString()), new Claim("FirstName", user.FirstName), new Claim("LastName", user.LastName) }; ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); return(claimsIdentity); }
public HttpResponseMessage Post([FromBody] UserLoginDTO value) { UserIdentityDTO user = null; if (ModelState.IsValid) { if (CheckUser(value.Email, value.Password, out user)) { return(Request.CreateResponse(HttpStatusCode.OK, JwtManager.GenerateToken(user))); } } var message = " Not valid logination data."; if (user != null && user.Blocked == true) { message = "This user is blocked!"; } return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, message)); }
private void CreateUserIdentity(string userId, string email, string token) { UserIdentityDTO userIdentityDTO = new UserIdentityDTO() { UserId = userId, Email = email }; string url = "http://localhost:51639/api/identity/updateUserProfile"; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("x-token", token); var result = client.PostAsJsonAsync(url, userIdentityDTO).Result; if (!result.IsSuccessStatusCode) { throw new FaildToConnectDbException(); } } }
protected Task <IPrincipal> AuthenticateJwtToken(string token) { if (ValidateToken(token, out string email, out string userrole)) { UserIdentityDTO userDTO = userService.GetByEmail(email); var claims = new List <Claim> { new Claim(ClaimTypes.Role, userrole), new Claim("Id", userDTO.Id.ToString()), new Claim(ClaimTypes.Name, userDTO.FirstName) }; var identity = new ClaimsIdentity(claims, "Jwt"); IPrincipal user = new ClaimsPrincipal(identity); return(Task.FromResult(user)); } return(Task.FromResult <IPrincipal>(null)); }
public async Task <ActionResult> VerifyTokenAsync(string token) { try { if (JwtManager.ValidateToken(token, out string userEmail, out string userrole)) { UserIdentityDTO user = await userService.GetByEmailAsync(userEmail); if (user == null) { return(BadRequest("User not found")); } return(Ok(user.Id)); } return(BadRequest("Token no longer valid")); } catch (Exception e) { return(StatusCode(500)); } }
public async Task <ActionResult> SendEmailConfirmLinkAsync([FromBody] EmailDTO emailModel, string emailConfirmLink) { try { if (emailConfirmLink == null) { var message = "Email confirmation link not found"; return(BadRequest(message)); } if (ModelState.IsValid) { UserIdentityDTO user = await userService.GetByEmailAsync(emailModel.Email); if (user == null) { return(NoContent()); } if (user.EmailConfirmed) { var message = "Email already confirmed"; return(Forbid(message)); } string token = JwtManager.GenerateToken(user, 0, 1); await EmailService.SendConfirmPasswordEmail(user.Email, token, emailConfirmLink); var mes = "Token successfully sent"; return(Ok(mes)); } var mess = "Email is not valid"; return(BadRequest(mess)); } catch (Exception e) { logger.LogInformation("Error : {0}", e.Message); return(StatusCode(500)); } }
public static UserIdViewModel Map(UserIdentityDTO user) { return(new UserIdViewModel { Role = Map(user.Role), Name = user.Name, IdentityId = user.IdentityId }); }
public async Task <ActionResult> FacebookPost([FromBody] FacebookDTO value) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={Facebook.AppId}&client_secret={Facebook.AppSecret}&grant_type=client_credentials"); var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse); var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={value.AccessToken}&access_token={appAccessToken.AccessToken}"); var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse); if (!userAccessTokenValidation.Data.IsValid) { return(BadRequest("Invalid facebook token!")); } var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v3.2/me?fields=id,email,first_name,last_name,name,picture&access_token={value.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse); var user = await userManager.FindByEmailAsync(userInfo.Email); if (user == null) { var userRole = await roleManager.FindByNameAsync("Student"); string picture = Convert.ToBase64String(await userService.GetImgBytesAsync(userInfo.Picture.Data.Url)); User newUser = new User { FirstName = userInfo.FirstName, LastName = userInfo.LastName, Email = userInfo.Email, UserName = userInfo.Email, Image = picture, Image_Name = userInfo.Name + "_Picture", Role = userRole, Role_Id = userRole.Id, EmailConfirmed = true }; var result = await userManager.CreateAsync(newUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); if (!result.Succeeded) { return(BadRequest()); } } var localUser = await userManager.FindByNameAsync(userInfo.Email); if (localUser == null) { return(BadRequest("Failed to create local user account.")); } var userDto = new UserIdentityDTO() { Email = localUser.Email, LastName = localUser.LastName, FirstName = localUser.FirstName, Id = localUser.Id, Role = localUser.Role.Name, EmailConfirmed = localUser.EmailConfirmed, Blocked = localUser.Blocked, Password = localUser.Password }; string jwt = JwtManager.GenerateToken(userDto); return(new JsonResult(jwt)); } catch (Exception e) { return(StatusCode(500)); } }
public async Task <int> DeleteAsync(UserIdentityDTO entity) { return(await genericRepository.DeleteAsync(mapper.Map <UserIdentity>(entity))); }
public async Task <int> AddAsync(UserIdentityDTO entity) { entity.Id = Guid.NewGuid(); return(await genericRepository.AddAsync(mapper.Map <UserIdentity>(entity))); }
public async Task <ActionResult> GooglePost([FromBody] GoogleDTO value) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { var validateToken = await Client.GetStringAsync($"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={value.AccessToken}"); var userInfoResponse = await Client.GetStringAsync($"https://www.googleapis.com/oauth2/v1/userinfo?access_token={value.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <GoogleUserData>(userInfoResponse); var user = await userManager.FindByEmailAsync(userInfo.Email); if (user == null) { var userRole = await roleManager.FindByNameAsync("Student"); string picture = Convert.ToBase64String(await userService.GetImgBytesAsync(userInfo.Picture)); User newUser = new User { FirstName = userInfo.FirstName, LastName = userInfo.LastName, Email = userInfo.Email, UserName = userInfo.Email, Image = picture, Image_Name = userInfo.Name + "_Picture", Role = userRole, Role_Id = userRole.Id, EmailConfirmed = true }; var result = await userManager.CreateAsync(newUser, Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 8)); if (!result.Succeeded) { return(BadRequest()); } } var localUser = await userManager.FindByNameAsync(userInfo.Email); if (localUser == null) { return(BadRequest("Failed to create local user account.")); } var userDto = new UserIdentityDTO() { Email = localUser.Email, LastName = localUser.LastName, FirstName = localUser.FirstName, Id = localUser.Id, Role = localUser.Role.Name, EmailConfirmed = localUser.EmailConfirmed, Blocked = localUser.Blocked, Password = localUser.Password }; string jwt = JwtManager.GenerateToken(userDto); return(new JsonResult(jwt)); } catch (Exception e) { return(StatusCode(500)); } }
public async Task <int> UpdateAsync(UserIdentityDTO entity) { return(await userIdentityRepository.UpdateAsync(entity)); }
public async Task <int> DeleteAsync(UserIdentityDTO entity) { return(await userIdentityRepository.DeleteAsync(entity.Id)); }