/// <summary> /// 将验证邮件的验证码写入数据库 /// </summary> /// <param name="param"></param> public void SendAuthEmail(SendAuthEmailParameter param) { using (var context = base.CreateUserContext()) { if (param.Kind != AuthEmailKind.ChangeEmail && !context.Accounts.Any(t => t.AppID == param.AppID && t.Email == param.Email)) { throw new InvalidInvokeException("Email不存在"); } string userName = context.Accounts.Where(t => t.AppID == param.AppID && t.RowID == param.UserID).Select(t => t.UserName).Single(); Guid authCode = Guid.NewGuid(); switch (param.Kind) { case AuthEmailKind.SignUp: case AuthEmailKind.ChangeEmail: Utility.SendVerifyEmail(param.AppID, userName, param.Email, authCode); break; case AuthEmailKind.FindPassword: Utility.SendFindPwdEmail(param.AppID, userName, param.Email, authCode); break; } var entity = new EmailAuth(); EntityMapper.Map <SendAuthEmailParameter, EmailAuth>(param, entity); entity.AuthKey = authCode.ToString(); entity.CreateDate = DateTime.Now; entity.Status = (int)ActivationStatus.NotActive; context.EmailAuths.Add(entity); context.SaveChanges(); } }
public User ChangePassword(string password, string code) { EmailAuth emailAuth = _emailAuth.Find(x => x.Token.Equals(code)).FirstOrDefault(); if (emailAuth == null) { return(null); } User user = _users.Find(x => x.Email.Equals(emailAuth.UserEmail)).FirstOrDefault(); if (user == null) { return(null); } byte[] passwordHash, passwordSalt; CreatePasswordHash(password, out passwordHash, out passwordSalt); user.PasswordHash = passwordHash; user.PasswordSalt = passwordSalt; _users.ReplaceOne(temp => temp.Id == user.Id, user); return(user); }
public void ChangePassword(ChangePasswordParameter param) { using (var context = base.CreateUserContext()) { EmailAuth emailAuth = null; MobileAuth mobileAuth = null; if (param.AuthCode != null) { Guid emailAuthCode; if (Guid.TryParse(param.AuthCode, out emailAuthCode)) { emailAuth = this.CheckUserEmailAuth(context, emailAuthCode); } else { string[] mobileAuthCode = param.AuthCode.Split(','); if (mobileAuthCode.Length != 2) { throw new InvalidInvokeException("参数错误"); } mobileAuth = this.CheckUserMobileAuth(context, mobileAuthCode[0], int.Parse(mobileAuthCode[1])); param.UserName = mobileAuth.UserName; } } var id = this.SignIn(new SignInParameter() { AppID = param.AppID, UserName = param.UserName, Password = param.OldPassword }); if (!id.IsAuthenticated) { throw new InvalidInvokeException("账户不存在或密码错误"); } using (var scope = DbScope.Create()) { scope.BeginTransaction(); param.NewPassword = CryptoManaged.MD5Hex(param.NewPassword); context.Accounts.Update(t => t.RowID == id.UserID, t => new Account() { Password = param.NewPassword }); if (emailAuth != null) { emailAuth.Status = (int)ActivationStatus.Activated; } if (mobileAuth != null) { mobileAuth.Status = (int)ActivationStatus.Activated; } context.SaveChanges(); scope.Complete(); } } }
public FirebaseAuthImplementation() { _firebaseAuth = FirebaseAuth.DefaultInstance; _emailAuth = new EmailAuth(); _googleAuth = new GoogleAuth(); _facebookAuth = new FacebookAuth(); _phoneNumberAuth = new PhoneNumberAuth(); }
public FirebaseAuthImplementation() { _firebaseAuth = FirebaseAuth.Instance; _emailAuth = new EmailAuth(); _googleAuth = new GoogleAuth(Activity, _googleRequestIdToken); _facebookAuth = new FacebookAuth(); _phoneNumberAuth = new PhoneNumberAuth(); }
public void OnLoginEditor() { var emailAuth = new EmailAuth(); emailAuth.FetchToken().ContinueWith((task) => { _auth.Login(task.Result).ContinueWith((t) => { ShowAuthData(); }); }); }
public LoginRes LogInViaEmail(string email, string password) { //Required repos IRepo <EmailAuth> emailAuthRepo = this.unitOfWork.EmailAuthRepo; IRepo <UserProfile> userProfileRepo = this.unitOfWork.UserProfileRepo; //Get auth with email IEnumerable <EmailAuth> auths = emailAuthRepo.Get(x => x.Email == email); if (auths.Count() == 0) { throw new InvalidCredentialsException(); } EmailAuth auth = auths.ElementAt(0); //Check password if (!this.hasher.CompareWithHash(password, auth.HashedPassword)) { throw new InvalidCredentialsException(); } //Get user UserProfile user = userProfileRepo.Get(auth.UserId); UserDto userDto = Mapper.Map <UserDto>(user); //Create jwt string jwt = this.jwtService.CreateToken( user.Id.ToString(), JwtService.DEFAULT_ISSUER, JwtService.DEFAULT_AUDIENCE, DateTime.UtcNow, DateTime.UtcNow.AddHours(JWT_LIFETIME_IN_HOURS), new Dictionary <string, string> { } ); //Return login response LoginRes loginRes = new LoginRes { JWT = jwt, User = userDto }; return(loginRes); }
public User ForgotPassword(string emailAddress) { User user = _users.Find(x => x.Email.Equals(emailAddress)).FirstOrDefault(); if (user == null) { return(null); } var expiry = 60; var token = Guid.NewGuid(); var emailAuth = new EmailAuth() { UserEmail = user.Email, Token = token, TimeStamp = DateTime.UtcNow, Expire = DateTime.UtcNow.AddSeconds(expiry) }; _emailAuth.InsertOne(emailAuth); SmtpClient client = new SmtpClient("smtp.gmail.com"); client.Port = 587; client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential(_settings.Key, _settings.Value); MailMessage msg = new MailMessage(); msg.From = new MailAddress("*****@*****.**"); msg.To.Add(emailAddress); msg.Subject = "Vuelo Email Verification"; var redirect = "https://localhost:5001/resetPassword"; msg.Body = string.Format("Please copy this to the verification field: {0} <br>" + "Click the <a href=\'{1}'> link </a> to verify password", token, redirect); msg.IsBodyHtml = true; client.Send(msg); return(user); }
public LoginRes RegisterEmail(Guid userId, string email, string password) { //Required repos IRepo <EmailAuth> emailAuthRepo = this.unitOfWork.EmailAuthRepo; IRepo <UserProfile> userProfileRepo = this.unitOfWork.UserProfileRepo; //Ensure user exists UserProfile user = userProfileRepo.Get(userId); if (user == null) { throw new DoesNotExistException(); } //Check if email is already registered IEnumerable <EmailAuth> auths = emailAuthRepo.Get(x => x.Email == email); if (auths.Count() > 0) { throw new AlreadyExistsException(); } //Hash password password = this.hasher.Hash(password); //Register email EmailAuth auth = new EmailAuth { UserId = userId, Email = email, HashedPassword = password }; do { auth.Id = Guid.NewGuid(); } while (emailAuthRepo.Exists(auth.Id)); emailAuthRepo.Insert(auth); //Create UserDto UserDto userDto = Mapper.Map <UserDto>(user); //Create jwt string jwt = this.jwtService.CreateToken( user.Id.ToString(), JwtService.DEFAULT_ISSUER, JwtService.DEFAULT_AUDIENCE, DateTime.UtcNow, DateTime.UtcNow.AddHours(JWT_LIFETIME_IN_HOURS), new Dictionary <string, string> { } ); //Return login response LoginRes loginRes = new LoginRes { JWT = jwt, User = userDto }; return(loginRes); }
public void RegisterExistingEmail() { //Automapper AutoMapperConfig.RegisterMappings(); //Mock repos Mock <IRepo <EmailAuth> > mockEmailAuthRepo = new Mock <IRepo <EmailAuth> >(); Mock <IRepo <UserProfile> > mockUserProfileRepo = new Mock <IRepo <UserProfile> >(); //Test user UserProfile testUser = new UserProfile { Id = Guid.NewGuid(), FirstName = "John", LastName = "Doe", Permissions = new List <Permission>() }; UserDto testUserDto = Mapper.Map <UserDto>(testUser); //Test auth EmailAuth testAuth = new EmailAuth { Id = Guid.NewGuid(), UserId = testUser.Id, Email = "*****@*****.**", HashedPassword = "******" }; //Test login response LoginRes testLoginRes = new LoginRes { JWT = "JWT", User = testUserDto }; //Mock calls mockEmailAuthRepo.Setup(x => x.Get( It.IsAny <Expression <Func <EmailAuth, bool> > >(), -1, -1, It.IsAny <Func <IQueryable <EmailAuth>, IOrderedQueryable <EmailAuth> > >(), "" )).Returns(new List <EmailAuth> { testAuth }); mockEmailAuthRepo.Setup(x => x.Exists(It.IsAny <Guid>())).Returns(false); mockUserProfileRepo.Setup(x => x.Get(It.Is <Guid>(y => y == testUser.Id))).Returns(testUser); //Mock unit of work Mock <IUnitOfWork> mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork.SetupGet(x => x.UserProfileRepo).Returns(mockUserProfileRepo.Object); mockUnitOfWork.SetupGet(x => x.EmailAuthRepo).Returns(mockEmailAuthRepo.Object); //Mock hasher Mock <IHasher> mockHasher = new Mock <IHasher>(); mockHasher.Setup(x => x.Hash(testAuth.HashedPassword)).Returns(testAuth.HashedPassword); //Mock jwt service Mock <IJwtService> mockJwtService = new Mock <IJwtService>(); mockJwtService.Setup(x => x.CreateToken( testUser.Id.ToString(), JwtService.DEFAULT_ISSUER, JwtService.DEFAULT_AUDIENCE, It.IsAny <DateTime>(), It.IsAny <DateTime>(), It.IsAny <Dictionary <string, string> >() )).Returns(testLoginRes.JWT); //Auth service AuthService authService = new AuthService(mockHasher.Object, mockUnitOfWork.Object, mockJwtService.Object); //Test LoginRes loginRes = authService.RegisterEmail(testUser.Id, testAuth.Email, testAuth.HashedPassword); TestUtil.Compare(loginRes, testLoginRes); }
protected override void Seed(FortuneDbContext context) { //Permissions Permission[] permissions = new Permission[] { new Permission { Id = Guid.NewGuid(), Name = "EditUsers" }, new Permission { Id = Guid.NewGuid(), Name = "EditPermissions" }, new Permission { Id = Guid.NewGuid(), Name = "EditTrailers" }, new Permission { Id = Guid.NewGuid(), Name = "EditLocations" }, new Permission { Id = Guid.NewGuid(), Name = "EditLoads" }, new Permission { Id = Guid.NewGuid(), Name = "ViewLoads" } }; context.Permissions.AddRange(permissions); //User Profiles UserProfile[] userProfiles = new UserProfile[] { new UserProfile { Id = Guid.NewGuid(), FirstName = "Ryan", LastName = "Helmoski", Permissions = permissions.ToList() } }; context.UserProfiles.AddRange(userProfiles); //Email Auths EmailAuth[] emailAuths = new EmailAuth[] { new EmailAuth { Id = Guid.NewGuid(), UserId = userProfiles[0].Id, Email = "*****@*****.**", HashedPassword = "******" } }; context.EmailAuths.AddRange(emailAuths); //Locations Location[] locations = new Location[] { new Location { Id = Guid.NewGuid(), Name = "Test Location 1" }, new Location { Id = Guid.NewGuid(), Name = "Test Location 2" }, new Location { Id = Guid.NewGuid(), Name = "Test Deleted Location", Deleted = true } }; context.Locations.AddRange(locations); //Trailers Trailer[] trailers = new Trailer[] { new Trailer { Id = 111111, LocationId = locations[0].Id }, new Trailer { Id = 222222, LocationId = locations[0].Id }, new Trailer { Id = 333333, LocationId = locations[0].Id, Deleted = true } }; context.Trailers.AddRange(trailers); //Loads Load[] loads = new Load[] { new Load { Id = Guid.NewGuid(), Type = LoadType.Inbound, Status = LoadStatus.InTransit, TrailerId = trailers[0].Id, Appointment = null, DepartureTime = DateTime.UtcNow.AddDays(-3), ArrivalTime = DateTime.UtcNow, OriginId = locations[0].Id, DestinationId = locations[1].Id, CfNum = 12345, PuNum = null }, new Load { Id = Guid.NewGuid(), Type = LoadType.Outbound, Status = LoadStatus.Ready, TrailerId = trailers[1].Id, Appointment = DateTime.UtcNow.AddHours(1), DepartureTime = null, ArrivalTime = DateTime.UtcNow, OriginId = locations[1].Id, DestinationId = locations[0].Id, CfNum = 54321, PuNum = 51423 }, new Load { Id = Guid.NewGuid(), Type = LoadType.Intraplant, Status = LoadStatus.Complete, TrailerId = trailers[1].Id, Appointment = null, DepartureTime = null, ArrivalTime = DateTime.UtcNow, OriginId = locations[1].Id, DestinationId = locations[0].Id, CfNum = null, PuNum = null }, new Load { Id = Guid.NewGuid(), Type = LoadType.LocalDelivery, Status = LoadStatus.InTransit, TrailerId = trailers[1].Id, Appointment = DateTime.UtcNow.AddMinutes(30), DepartureTime = DateTime.UtcNow, ArrivalTime = null, OriginId = locations[1].Id, DestinationId = locations[0].Id, CfNum = null, PuNum = null } }; context.Loads.AddRange(loads); context.SaveChanges(); }
public async Task <IActionResult> InviteUserToRole(IFormCollection collection) { var rawRole = collection["RoleId"].ToString(); var roleId = int.Parse(rawRole); EmailHelper helper = new EmailHelper(); var user = await _userManager.FindByIdAsync(collection["UserId"]); var hashCode = helper.RandomString(32); var Role = _context.Roles .FirstOrDefault(x => x.Id == roleId); var emailAuth = new EmailAuth() { Id = 0, Hash = hashCode, RoleId = Role.Id, UserId = user.Id }; _context.EmailAuths.Add(emailAuth); _context.SaveChanges(); var connectionURL = "smtp.gmail.com"; var emailUsername = "******"; var emailPassword = "******"; var hostname = "https://*****:*****@thehighlandersmuseum.com"); message.From.Add(from); MailboxAddress to = new MailboxAddress(user.Forename + " " + user.Surname, user.Email); message.To.Add(to); message.Subject = "You have been invited to a new role!"; var linkURL = hostname + "/Account/Manage/Invite?code=" + hashCode; BodyBuilder bodyBuilder = new BodyBuilder(); using (StreamReader SourceReader = System.IO.File.OpenText(emailTemplate)) { bodyBuilder.HtmlBody = string.Format(SourceReader.ReadToEnd(), user.Forename, user.Surname, Role.Name, linkURL, linkURL ); } message.Body = bodyBuilder.ToMessageBody(); SmtpClient client = new SmtpClient(); client.Connect(connectionURL, 25, false); client.Authenticate(emailUsername, emailPassword); //client.Authenticate("insert gmail email", "insert gmail password"); client.Send(message); client.Disconnect(true); client.Dispose(); return(RedirectToAction("Index")); }