public async Task <Session> RegisterAsync(RequestUser userForRegister) { if (userForRegister == null) { return(null); } //generate password hash var passwordHash = _hashGenerator.GenerateHash(userForRegister.Password); //create user var user = new User { UserName = userForRegister.UserName, GamerInfo = new GamerInfo(userForRegister.UserName), PasswordHash = passwordHash }; //try to add new user if (!await _storage.TryAddUserAsync(user)) { return(null); } //get token for new user var token = _tokenGenerator.GenerateToken(user.UserName, user.PasswordHash); //return new session with token return(new Session { UserName = user.UserName, GamerInfo = user.GamerInfo, Token = token }); }
public async Task <LoginResponseModel> Login(LoginDto model) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure : false); if (!result.Succeeded) { throw new AuthException(result.IsLockedOut ? "User account locked out." : "Invalid login or password"); } var user = await _userManager.FindByEmailAsync(model.Email) ?? await _userManager.FindByNameAsync(model.Email); var roles = await _userManager.GetRolesAsync(user); var authToken = _tokenGenerator.GenerateToken(user, roles); return(new LoginResponseModel { AuthToken = authToken, RememberMe = model.RememberMe, QrCode = string.Empty, User = new AutorizedUserResponseModel { Id = user.Id, FirstName = user.FirstName, Surname = user.Surname } }); }
/// <summary> /// Authenticate user using username and password and create the token /// </summary> /// <param name="user"></param> /// <returns>generated token</returns> public AuthRequest AuthenticateUser(User user) { try { User response = null; AuthRequest token = null; response = _user.GetUser(user); if (!string.IsNullOrEmpty(response.Password)) { response.Password = DecodeFrom64(response.Password); } if (response != null && response.Password.Equals(user.Password)) { //JwtTokenGenerator jwt = new JwtTokenGenerator(_config); token = _jwtTokenGenerator.GenerateToken(response); } return(token); } catch (Exception ex) { throw ex; } }
public async Task <LoginResultApiModel> LogInAsync(string firebaseToken, string phoneNumber) { var auth = FirebaseAuth.GetAuth(FirebaseApp.DefaultInstance); //this can throw detailed error message. var verified = await auth.VerifyIdTokenAsync(firebaseToken); var identityUser = await usersRepository.GetByIdAsync(verified.Uid); //user confirmed his phone number, but has not registered yet; //Register him now in that case var isNewUser = false; if (identityUser == null) { try { var username = "******" + Guid.NewGuid(); identityUser = await RegisterNewUserAsync(new RegisterModel { PhoneNumber = phoneNumber, UserName = username, Id = verified.Uid }); isNewUser = true; } catch (Exception ex) { throw new InvalidDataException("Couldn't register this user.", ex); } } else { if (identityUser.PhoneNumber != phoneNumber) { throw new UnauthorizedAccessException("Please provide a phone number that correlates to firebase JWT token."); } } return(new LoginResultApiModel { Info = identityUser.ToAppUserDto(), Token = tokenGenerator.GenerateToken(identityUser), RefreshToken = identityUser.RefreshToken, IsNewUser = isNewUser }); }
public async Task <SignInResponse> Handle(SignInCommand request, CancellationToken cancellationToken) { try { var user = await _userManager.FindByEmailAsync(request.Email); if (user == null) { throw new NotFoundException(request.Email); } var signInResult = await _signInManager.CheckPasswordSignInAsync(user, request.Password, true); if (!signInResult.Succeeded) { throw new UnauthorizedAccessException("Wrong username or password"); } var identity = await GetIdentityClaims(user); var token = _jwtTokenGenerator.GenerateToken(user, identity, request.RememberMe); return(new SignInResponse(token)); } catch (Exception e) { throw new UnauthorizedAccessException(e.Message, e.InnerException); } }
public async Task Invoke( HttpContext context, IJwtTokenGenerator generator) { if (context?.Items?.Any() == true) { string token; if (context.Items.ContainsKey(Constants.MiddlewareTokenPassingKey)) { token = (string)context.Items[Constants.MiddlewareTokenPassingKey]; } else { token = generator.GenerateToken(context .User .Claims .ToArray()); } context .Response .Headers .Add("Token", token); if (context.Items.ContainsKey(Constants.MiddlewareTokenPassingKey)) { context.Response.StatusCode = StatusCodes.Status201Created; return; } } await _next(context); }
public async Task <Result <LoginOutputModel> > Login(LoginUserCommand userInput) { var user = await userManager.FindByEmailAsync(userInput.Email); if (user == null) { return(IdentityErrors.InvalidLogin); } var passwordValid = await userManager.CheckPasswordAsync(user, userInput.Password); if (!passwordValid) { return(IdentityErrors.InvalidLogin); } var userRoles = await this.userManager.GetRolesAsync(user); var claimRoles = new List <Claim>(); if (userRoles.Any()) { foreach (var roleName in userRoles) { claimRoles.Add(new Claim(ClaimTypes.Role, roleName)); } } var token = jwtTokenGenerator.GenerateToken(user, claimRoles); return(new LoginOutputModel(token)); }
public IActionResult GetToken([FromQuery] string keyId, [FromQuery] string tokenType = "client", [FromQuery] ushort expiresSec = 90) { tokenType ??= "client"; var claims = new List <Claim>(); switch (tokenType.ToLower()) { case "admin": claims.Add(new Claim("x-admin-access", "true")); break; case "client": claims.Add(new Claim("x-client-access", "true")); break; case "provisioning": claims.Add(new Claim("x-provisioning-access", "true")); break; case "all": claims.Add(new Claim("x-admin-access", "true")); claims.Add(new Claim("x-client-access", "true")); claims.Add(new Claim("x-provisioning-access", "true")); break; } ; try { var token = _tokenGenerator.GenerateToken(claims, keyId, expiresSec); return(Ok(new { jwt = token.Token, unixTimeExpiresAt = token.ExpiresAt, expiresAt = UnixTimeStampToDateTime(token.ExpiresAt).ToString() })); } catch (ArgumentOutOfRangeException ex) { return(BadRequest(new { Error = "KeyId not existing" })); } catch (Exception ex) { return(BadRequest(new { Error = "Unknown exception", Exception = ex })); } }
public async Task <IActionResult> SignIn([FromBody] ManageConversationAuthenticationRequest request) { string manageId = request.ManageId; logger.LogInformation("Attempting to gather managing information for the id '{0}'", manageId); IActionResult actionResult; ExecutionResult executionResult = await manageConversationLinkService.ValidateAndMarkVisitedAsync(manageId); if (executionResult.IsSuccess) { logger.LogInformation("Generating temporary access token for conversation id '{0}'", manageId); string token = tokenGenerator.GenerateToken($"temp-manage-user-{manageId}"); TokenResponse tokenResponse = new TokenResponse(token); logger.LogInformation("Generated temporary access token for conversation id '{0}'", manageId); actionResult = Ok(tokenResponse); } else { actionResult = NotFound(); } return(actionResult); }
public void GetJwt_GetsValidJwt() { var token = _tokenGenerator.GenerateToken(_testUser.Id); // validate token var tokenHandler = new JwtSecurityTokenHandler(); var validationParameters = new TokenValidationParameters { IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_testSettings.JwtSecret)), ValidateAudience = false, ValidateIssuer = false, ValidateLifetime = false, ValidateActor = false, }; try { tokenHandler.ValidateToken(token, validationParameters, out _); } catch (Exception e) { Assert.True(false, e.Message); } Assert.True(true); }
public async Task <IActionResult> Register([FromBody] RegModel model) { try { var emailExists = await _userManager.FindByEmailAsync(model.Email); if (emailExists != null) { throw new ValidationException("Email Already exists."); } var userDetails = new User() { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, EmailConfirmed = true, IsDeleted = false, EmailNotification = true, SmsNotification = true }; var result = await _userManager.CreateAsync(userDetails, model.Password); if (!result.Succeeded) { throw new ValidationException("Registration failed."); } await _userManager.AddToRoleAsync(userDetails, "doctor"); var jwt = await _jwtTokenGenerator.GenerateToken(userDetails); JObject returnData = new JObject(); returnData["token"] = jwt; return(Ok(returnData.ToString())); } catch (Exception ex) { return(Ok(new JObject { ["error"] = ErrorCodes.GetCode("GenericError"), ["Message"] = ex.Message }.ToString())); } }
public async Task <InstituteRegirstrationModel> RegisterNewInstitute(InstituteRegirstrationModel model) { var userDetails = new User() { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, EmailConfirmed = true, IsDeleted = false, EmailNotification = true, SmsNotification = true, }; var emailExists = await _userManager.FindByEmailAsync(model.Email); if (emailExists != null) { throw new ValidationException("Email Already exists."); } var result = await _userManager.CreateAsync(userDetails, model.Password); if (!result.Succeeded) { throw new ValidationException("Registration failed."); } await _userManager.AddToRoleAsync(userDetails, "admin"); string jwt = await _jwtTokenGenerator.GenerateToken(userDetails); model.Token = jwt; Institution objInstitution = new Institution { InstituteName = model.InstituteName, Hostnames = model.Hostname, IdNumber = model.IdNumber, IdType = model.IdType, Status = "Active", AdministratorId = userDetails.Id, Type = (InstitutionType)model.InstitutionType }; _dbContext.Institutions.Add(objInstitution); await _dbContext.SaveChangesAsync(); return(model); }
public async Task <PatientModel> RegisterPatient(PatientModel model) { try { var emailExists = await _userManager.FindByNameAsync(model.Username); if (emailExists != null) { throw new ValidationException("Email Already exists."); } var userDetails = new User() { UserName = model.Username, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, EmailConfirmed = true, IsDeleted = false, EmailNotification = true, SmsNotification = true }; var result = await _userManager.CreateAsync(userDetails, "PatientLogin123!"); if (!result.Succeeded) { throw new ValidationException("Registration failed."); } await _userManager.AddToRoleAsync(userDetails, "patient"); var patient = model.MapTo <Patient>(); patient.UserId = userDetails.Id; _dbContext.Patients.Add(patient); await _dbContext.SaveChangesAsync(); var jwt = await _jwtTokenGenerator.GenerateToken(userDetails); model.Token = jwt; return(model); } catch (Exception ex) { return(null); } }
public async Task <ActionResult> RegisterUser([FromBody] RegisterRequest data) { var user = _mapper.Map <User>(data); var result = await _userManager.CreateAsync(user, data.Password); if (!result.Succeeded) { return(BadRequest(result.Errors.Where(e => e.Code != "DuplicateUserName"))); } var userResponse = _mapper.Map <UserAndTokenResponse.UserAndTokenUserResponse>(user); var token = _tokenGenerator.GenerateToken(user.Id); return(Ok(new UserAndTokenResponse { User = userResponse, Token = token })); }
public async Task <UserLoginViewModel> Handle(UserLoginQuery request, CancellationToken cancellationToken) { var user = await _context.Users.FirstOrDefaultAsync(x => x.Email.Equals(request.Email, StringComparison.OrdinalIgnoreCase)); if (user == null) { return new UserLoginViewModel { Success = false, Message = "Invalid email or password." } } ; var verified = _hashGenerator.CheckHash(user.PasswordHash, request.Password); if (!verified) { return new UserLoginViewModel { Success = false, Message = "Invalid email or password." } } ; var accessToken = _tokenGenerator.GenerateToken(user.LastName, user.Email, user.Id); return(new UserLoginViewModel { Success = true, AccessToken = accessToken, User = new UserInfo { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, UserId = user.Id, Image = user.ProfilePicture != null ? user.ProfilePicture : _placeHolderImageProvider.GetProfileImagePlaceHolder() } }); } } }
public async Task <UserLoginViewModel> Handle(UserRegisterCommand request, CancellationToken cancellationToken) { var userExists = await _userRepository.UserExists(request.Email); if (userExists) { return new UserLoginViewModel { Success = false, Message = "User already exists." } } ; var passwordHash = _hashGenerator.ComputeHash(request.Password); var user = AppUser.Create( firstname: request.FirstName, lastname: request.LastName, email: request.Email, passwordHash: passwordHash); await _userRepository.AddAsync(user); await _unitOfWork.SaveChangesAsync(CancellationToken.None); var accessToken = _tokenGenerator.GenerateToken(user.LastName, user.Email, user.Id); return(new UserLoginViewModel { Success = true, AccessToken = accessToken, User = new UserInfo { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, UserId = user.Id, Image = user.ProfilePicture ?? _placeholderImageProvider.GetProfileImagePlaceHolder() } }); } }
public async Task <IActionResult> OnPostAsync() { var client = await _context.DeveloperApps.SingleOrDefaultAsync(x => x.AppId == Guid.Parse(ClientId)); if (client == null) { ModelState.AddModelError("", "invalid client_id"); return(Page()); } client.RequiresConsent = false; _context.DeveloperApps.Update(client); await _context.SaveChangesAsync(CancellationToken.None); var userId = client.UserId; var user = await _context.Users.SingleOrDefaultAsync(x => x.Id == userId); var token = _tokenGenerator.GenerateToken(user.LastName, user.Email, user.Id); return(Redirect($"{RedirectUri}#{token}")); }
public async Task <LoginDto> Login(LoginQuery request) { var user = await _userManager.FindByNameAsync(request.UserName); if (user == null) { return(null); } var passwordValid = await _userManager.CheckPasswordAsync(user, request.Password); if (!passwordValid) { return(null); } var token = _jwtTokenGenerator.GenerateToken(user); return(new LoginDto { Token = token }); }
public async Task <IActionResult> CheckIfExisitsAndLogin([FromBody] PatientModel model) { try { string username = model.Email != null ? model.Email : model.PhoneNumber; var userDetails = await _userManager.FindByNameAsync(username); if (userDetails != null) { var isPatient = await _userManager.IsInRoleAsync(userDetails, "patient"); if (isPatient) { var result = await _userManager.CheckPasswordAsync(userDetails, "PatientLogin123!"); if (result) { var jwt = await _jwtTokenGenerator.GenerateToken(userDetails); JObject returnData = new JObject(); returnData["token"] = jwt; returnData["role"] = "patient"; returnData["Email"] = model.Email; return(Ok(returnData.ToString())); } } else { throw new GenericException(ErrorCodes.GetCode("UserNotPatient")); } } else { var provider = await _manager.RegisterPatient(new PatientModel { Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, Username = username }); if (provider != null) { JObject returnData = new JObject(); returnData["token"] = provider.Token; returnData["role"] = "patient"; returnData["Email"] = model.Email; return(Ok(returnData.ToString())); } } throw new GenericException(ErrorCodes.GetCode("UserNotFound")); } catch (GenericException ex) { return(Ok(new JObject { ["error"] = ex.Code }.ToString())); } catch (Exception ex) { return(Ok(new JObject { ["error"] = ex.Message }.ToString())); } }
public async Task <ExternalLoginResponse> Handle(ExternalLoginRequest request, CancellationToken cancellationToken) { try { var user = await _context.Users.FirstOrDefaultAsync(x => x.Email == request.Email, cancellationToken); // TODO: Extract this if (user == null) { var notificationSettings = EnumFactory.SeedEnum <NotificationType, NotificationSetting>((value, index) => new NotificationSetting() { Id = Guid.NewGuid(), NotificationType = value, }).ToList(); // call create user request.. var userId = Guid.NewGuid(); var newUser = new ApplicationUser() { Id = userId, AccountType = request.AccountType, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, ExternalLoginAccount = true, UserSetting = new UserSetting() { ApplicationUserId = userId, NotificationSettings = notificationSettings, }, }; if (request.Avatar != null) { newUser.Avatar = request.Avatar; } newUser.CustomerId = await StripeConfiguration.AddCustomer(newUser.FullName, newUser.Email); // add to stripe newUser = ExerciseTagGroupsFactory.ApplyProperties <ApplicationUser>(newUser); await _context.Users.AddAsync(newUser, cancellationToken); await _context.SaveChangesAsync(cancellationToken); user = newUser; } else if (user.ExternalLoginAccount == false) { throw new Exception("Can't external login user who exists but doesn't have external login enabled"); } var token = _tokenGenerator.GenerateToken(user.Id); var userInfo = await _mediator.Send(new CurrentUserRequest(user.Id), cancellationToken); return(new ExternalLoginResponse(token, userInfo)); } catch (Exception e) { throw new Exception(nameof(ExternalLoginRequest), e); } }
public async Task Invoke( HttpContext context, IJwtTokenGenerator generator, IIdentityResolver identityResolver, ILogger <PreAuthorizationMiddleware> logger) { var authorization = context.Request.Headers.SingleOrDefault(x => x.Key == "Authorization").Value.SingleOrDefault(); const string fluffySpoonAuthorizationPrefix = "FluffySpoon"; const string tokenAuthorizationPrefix = "Bearer"; if (authorization != null) { var credentials = new Credentials(null, null); if (authorization.StartsWith(fluffySpoonAuthorizationPrefix)) { try { var credentialsCode = authorization.Substring(fluffySpoonAuthorizationPrefix.Length).Trim(); if (!string.IsNullOrWhiteSpace(credentialsCode)) { var decoded = Encoding.UTF8.GetString(Convert.FromBase64String(credentialsCode)); credentials = JsonConvert.DeserializeObject <Credentials>(decoded); } } catch { logger.LogWarning("The given FluffySpoon authorization header was of an invalid format."); await _next(context); return; } var claimsResult = await identityResolver.GetClaimsAsync(credentials); if (claimsResult == null) { await _next(context); return; } var claims = claimsResult .Claims .Select(x => new Claim( x.Key, x.Value)) .ToList(); if (claims.Any(x => x.ValueType == ClaimTypes.Role)) { throw new InvalidOperationException("Can't provide roles through claims. Use the roles array instead of the claims result."); } foreach (var role in claimsResult.Roles) { claims.Add(new Claim( ClaimTypes.Role, role)); } if (credentials?.Username != null) { claims.Add(new Claim( JwtRegisteredClaimNames.Sub, credentials.Username)); } var token = generator.GenerateToken(claims.ToArray()); context.Items.Add(Constants.MiddlewareTokenPassingKey, token); } } await _next(context); }
public async Task <ProviderModel> RegisterNewProvider(ProviderModel model, int AdminId = 0) { var emailExists = await _userManager.FindByEmailAsync(model.Email); if (emailExists != null && !emailExists.IsDeleted) { throw new GenericException(ErrorCodes.GetCode("UserAlreadyExits")); } var userDetails = new User() { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, EmailConfirmed = true, IsDeleted = false, EmailNotification = true, SmsNotification = true }; var result = await _userManager.CreateAsync(userDetails, model.Password); if (!result.Succeeded) { throw new GenericException(ErrorCodes.GetCode("RegistrationFailed")); } await _userManager.AddToRoleAsync(userDetails, "doctor"); var provider = model.MapTo <Provider>(); provider.UserId = userDetails.Id; provider.Language = "eng"; if (model.InstituteId == 0) { var Institute = new Institution { InstituteName = model.InstituteName, Hostnames = "Temp", Status = "Active", }; _dbContext.Institutions.Add(Institute); await _dbContext.SaveChangesAsync(); provider.InstituteId = Institute.Id; } provider.AllowEmail = true; provider.AllowSMS = true; _dbContext.Providers.Add(provider); await _dbContext.SaveChangesAsync(); //foreach (SpecialityModel sm in model.Specialities) //{ // _dbContext.ProviderSpecialityMappings.Add(new ProviderSpecialityMapping // { // ProviderId = provider.Id, // SpecialityId = sm.SpecialityId // }); //} await _dbContext.SaveChangesAsync(); var jwt = await _jwtTokenGenerator.GenerateToken(userDetails); model.Token = jwt; var room = await CreateNewWaitingRoom(new WaitingRoomModel { RoomName = model.RoomName, ProviderId = provider.Id, Type = "Individual" }); _dbContext.RoomProviderMapping.Add(new RoomProviderMapping { RoomId = room.Id, ProviderId = provider.Id, IsActive = true, IsPrimaryOwner = true, }); if (AdminId != 0) { _dbContext.RoomProviderMapping.Add(new RoomProviderMapping { RoomId = room.Id, ProviderId = AdminId, IsActive = true, IsPrimaryOwner = false, }); } await _dbContext.SaveChangesAsync(); return(model); }
public async Task <UserLoginViewModel> Handle(UserExternalLoginQuery request, CancellationToken cancellationToken) { var user = await _externalAuthProvider.LoginExternal(request.Provider, request.AccessToken); if (user.Error != null) { return new UserLoginViewModel { Success = false, Message = user.Error } } ; var existingUser = await _userRepository.GetUserByEmail(user.Email); string accesstoken = string.Empty; if (existingUser == null) { var newUser = AppUser.Create( firstname: user.FirstName, lastname: user.LastName, email: user.Email, passwordHash: "" ); newUser.ProfilePicture = user.Picture; await _userRepository.AddAsync(newUser); await _unitOfWork.SaveChangesAsync(CancellationToken.None); accesstoken = _tokenGenerator.GenerateToken(newUser.LastName, newUser.Email, newUser.Id); return(new UserLoginViewModel { Success = true, AccessToken = accesstoken, User = new UserInfo { FirstName = newUser.FirstName, LastName = newUser.LastName, Email = newUser.Email, UserId = newUser.Id, Image = newUser.ProfilePicture } }); } if (existingUser.ProfilePicture == null && user.Picture != null) { existingUser.ProfilePicture = user.Picture; _userRepository.Update(existingUser); await _unitOfWork.SaveChangesAsync(CancellationToken.None); } accesstoken = _tokenGenerator.GenerateToken(existingUser.LastName, existingUser.Email, existingUser.Id); return(new UserLoginViewModel { Success = true, AccessToken = accesstoken, User = new UserInfo { FirstName = existingUser.FirstName, LastName = existingUser.LastName, Email = existingUser.Email, UserId = existingUser.Id, Image = existingUser.ProfilePicture } }); } }