Пример #1
0
            //http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
            public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
            {
                if (m_UserManager != null)
                {
                    CustomUser user = null;
                    user = await m_UserManager.FindByNameAsync(context.UserName);

                    string hashedPassword = CustomPasswordHasher.GetPasswordAfterHashing(context.Password, user);
                    if (string.Compare(user.PasswordHash, hashedPassword, System.StringComparison.Ordinal) != 0)
                    {
                        user = null;
                    }

                    if (user == null)
                    {
                        context.SetError("invalid_grant", "The user name or password is incorrect.");
                        return;
                    }

                    ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(m_UserManager, OAuthDefaults.AuthenticationType);


                    AuthenticationProperties properties = CreateProperties(user.UserName);
                    AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                    context.Validated(ticket);

                    //what is this for exactly?
                    ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(m_UserManager, CookieAuthenticationDefaults.AuthenticationType);

                    context.Request.Context.Authentication.SignIn(cookiesIdentity);
                }
            }
Пример #2
0
        public IActionResult Register(AccountRegister new_user)
        {
            using (GlobalDBContext _context = new GlobalDBContext())
            {
                string _domainurl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";
                // ->TODO Validation check on clinet side using Jquery or JavaScript

                // Password hashed with extra layer of security
                string password          = new_user.Password;
                CustomPasswordHasher pwd = new CustomPasswordHasher();
                // increse the size to increase secuirty but lower performance
                string salt   = pwd.CreateSalt(10);
                string hashed = pwd.HashPassword(password, salt);
                //new_user.Salt = salt;
                new_user.Password = hashed;
                // var errors = ModelState.Values.SelectMany(v => v.Errors);
                Role role    = _context.Roles.Find(new_user.UserRole);
                User theUser = new User();
                theUser.AddFromAccountRegsiter(new_user, role, salt);
                string uniqueToken = Guid.NewGuid().ToString("N").Substring(0, 6);
                theUser.UniqueToken = uniqueToken;
                _context.Users.Add(theUser);

                SendEmail email    = new SendEmail(_emailSettings);
                string    fullname = theUser.UserFirstName + " " + theUser.UserLastName;
                string    msg      = "Please verify you email account for the verification. Click on the link to verify :";
                msg += _domainurl + "/Account/ConfirmEmail?email=" + theUser.UserEmail + "&token=" + theUser.UniqueToken;

                _context.SaveChanges();
                email.SendEmailtoUser(fullname, theUser.UserEmail, "Email Verification", msg);
                ViewBag.Messsage = new_user.FirstName + " " + new_user.LastName + " successfully registered. A Email has been sent for the verfication.";
            }
            return(View());
        }
Пример #3
0
        public void AddNewUser()
        {
            var user = new User()
            {
                Email     = "*****@*****.**",
                FirstName = "Erandika",
                IsActive  = true,
                LastName  = "Sandaruwan",
                MobileNo  = "0702605650",
                Password  = CustomPasswordHasher.GenerateHash("system"),
                Username  = "******",
            };

            user.UserRoles = new HashSet <UserRole>();

            var userRole = new UserRole()
            {
                IsActive    = true,
                RoleId      = 1,
                StartedDate = DateTime.UtcNow
            };

            user.UserRoles.Add(userRole);
            _db.SaveChanges();
        }
Пример #4
0
        public async Task <IActionResult> ChangePassword([FromBody] Authenticate user)
        {
            if (user == null)
            {
                return(BadRequest(StaticVar.MessageNotFound));
            }
            //get user from DB
            UserTest dbUser = await _serviceUserTest.GetByIDAsync(user.Code).ConfigureAwait(false);

            if (dbUser == null)
            {
                return(BadRequest(StaticVar.MessageNotFound));
            }
            //kiểm tra password cũ có đúng không
            if (CustomPasswordHasher.VerifyPassword(dbUser.Password, user.OldPassword))
            {
                var passwordHashed = CustomPasswordHasher.HashPassword(user.Password);
                //đúng thì cho đổi password
                BsonDocument objBSON = new BsonDocument
                {
                    { "Password", passwordHashed }
                };
                await _serviceUserTest.UpdateCustomizeFieldByIdAsync(dbUser.Id, objBSON);

                return(Ok("Đổi password thành công"));
            }
            else
            {
                //sai thì báo lỗi
                return(BadRequest("User hoặc mật khẩu cũ không hợp lệ"));
            }
        }
Пример #5
0
        public ActionResult Login(User user)
        {
            User userEmail = ModelContext.Users.Where(u => u.Email == user.Email).SingleOrDefault();

            if (userEmail != null)
            {
                CustomPasswordHasher customPasswordHasher = new CustomPasswordHasher();

                bool pass = customPasswordHasher.CustomVerifyHashedPassword(userEmail.Password, user.Password);

                User userCredentials = ModelContext.Users.Where(a => a.Email.Equals(user.Email)).FirstOrDefault();

                if (userCredentials != null && pass)
                {
                    Session["UserID"] = userCredentials.UserId.ToString();
                    Session["Name"]   = userCredentials.Forename.ToString();

                    if (Session[UserIDKey] != null)
                    {
                        int userId = Convert.ToInt32(Session[UserIDKey]);
                        Cart_PM.MigrateCart(userId);
                    }


                    return(RedirectToAction("Index", "Home"));
                }
            }

            ViewBag.Message = "Incorrect Credentials";
            return(View(user));
        }
Пример #6
0
        public void ValidateUserAndPassword(string userName, string password)
        {
            var user = m_userRepository.GetByLogin(userName);

            if (user == null || user.PasswordHash == null || (!CustomPasswordHasher.ValidatePassword(password.Split(':')[1], user.PasswordHash)))
            {
                throw new AuthenticationException("Invalid credentials");
            }
        }
Пример #7
0
        private bool VerifyPassword(User user, string Password)
        {
            CustomPasswordHasher passwordHasher = new CustomPasswordHasher();

            if (passwordHasher.VerifyHashedPassword(user.Password, Password) == PasswordVerificationResult.Success)
            {
                return(true);
            }

            return(false);
        }
Пример #8
0
        /// <summary>
        /// validates password and saves it in DB
        /// </summary>
        /// <param name="resetPasswordInfo"></param>
        /// <returns></returns>
        public ValidationViewModel ValidateForgotPassword(UserLoginViewModel resetPasswordInfo)
        {
            ValidationViewModel response = new ValidationViewModel();

            try
            {
                if (!(string.IsNullOrEmpty(resetPasswordInfo.UserId) && string.IsNullOrEmpty(resetPasswordInfo.ForgotPasswordToken)))
                {
                    string userID = resetPasswordInfo.UserId;

                    UserLoginViewModel user = GetUserDetails(userID);

                    if (user != null && user.ForgotPasswordToken != null && user.ForgotPasswordToken.Equals(resetPasswordInfo.ForgotPasswordToken))
                    {
                        if (user.Password == null || !(user.Password.Equals(resetPasswordInfo.Password)))
                        {
                            CustomPasswordHasher customPasswordHasher = new CustomPasswordHasher();
                            user.Password            = customPasswordHasher.HashPassword(resetPasswordInfo.Password);
                            user.ForgotPasswordToken = null;
                            user.LastPasswordChanged = DateTime.Now;
                            if (UpdatePassword(user).Success)
                            {
                                response.Success        = true;
                                response.SuccessMessage = BusinessConstants.PASSWORD_SAVED;
                                return(response);
                            }
                        }
                        response.Success = false;
                        response.ErrorMessages.Add(BusinessConstants.CANNOT_REUSE_PASSWORD);
                        return(response);
                    }
                    else if (user != null && user.ForgotPasswordToken == null)
                    {
                        response.Success = false;
                        response.ErrorMessages.Add(BusinessConstants.LINK_EXPIRED);
                        return(response);
                    }
                    response.Success = false;
                    response.ErrorMessages.Add(BusinessConstants.CHANGE_IN_URL);
                    return(response);
                }
                response.ErrorMessages.Add(BusinessConstants.EMAIL_IS_EMPTY);
                response.Success = false;
            }
            catch (Exception ex)
            {
                _logger.Log(ex, LogLevel.Error, ex.Message);
                response.ErrorMessages.Add(BusinessConstants.ERROR_OCCURED);
                response.Success = false;
            }
            return(response);
        }
Пример #9
0
        static void Main(string[] args)
        {
            string password = "******";

            IdentityUser         user   = new IdentityUser();
            CustomPasswordHasher hasher = new CustomPasswordHasher();

            string hashedValue = hasher.HashPassword(user, password);

            Console.WriteLine("HashedValue > " + hashedValue);

            Console.WriteLine("Verify > " + hasher.VerifyHashedPassword(user, hashedValue, password));
        }
        public HttpResponseMessage Login(string LoginType, string UserName, string Password, string PushNotificationID, string MobilePlatform)
        {
            using (DBDataContext db = new DBDataContext())
            {
                List <usp_GetUserInformationResult> res = db.usp_GetUserInformation(LoginType, UserName).ToList();
                if (res.Count() > 0 && LoginType.ToUpper() == "EMAIL" && CustomPasswordHasher.VerifyHashedPassword(res.ElementAt(0).Password, Password))
                {
                    usp_GetUserInformationResult t = res.ElementAt(0);
                    db.usp_UpdateUserMobileDeviceInformation(t.ID, MobilePlatform, PushNotificationID);

                    PenYourPrayerUser user = new PenYourPrayerUser();
                    user.ID                 = t.ID;
                    user.DisplayName        = t.DisplayName;
                    user.LoginType          = t.LoginType;
                    user.UserName           = t.UserName;
                    user.MobilePlatform     = MobilePlatform;
                    user.ProfilePictureURL  = t.ProfilePictureURL;
                    user.PushNotificationID = PushNotificationID;
                    user.HMACHashKey        = t.HMACHashKey;
                    user.EmailVerification  = t.EmailVerification;
                    if (!t.EmailVerification)
                    {
                        user.HMACHashKey = "";
                    }
                    //

                    return(Request.CreateResponse(HttpStatusCode.OK, user));
                }
                //else if (res.Count() > 0 && LoginType.ToUpper() == "FACEBOOK")
                //{
                //    bool result = SocialMediaAuthentication.CheckFacebookAccessToken("CAAXXIYv53qcBABWf4lQvRT0Rm3UgBXcF1foQ4SRTNDp7eaSvDFLe4fZC4BFqsE1YYTcdUQw3UvZCRkmdWZAFbu2hav9UuHZAoE9VcpLkKvsSZC3IfLUrHglCygQ5XbZBcH0ORI9t2QzKAjggPsrORxmVgovoHZCzl4wV56mv9cQPxvZBxTCiOJlrcdbh5JigAxXnQ2h5Yc0WinZAjcypHhrgZAL8BnwiKOECTDNFXgOtfbDQZDZD");

                //}
                //else if (res.Count() > 0 && LoginType.ToUpper() == "TWITTER")
                //{
                //    bool result = SocialMediaAuthentication.checkTwitterAccessToken(UserName, "806837785-trTr0ObdqaW0owy1N0WXJFh6OGSlgUH74nh3qoHO", "w5j7WPwHWwY4DSfJ82tRVZF7SBogZJ6XABptVt431uOowvwFKC");
                //}
                //else if (res.Count() > 0 && LoginType.ToUpper() == "GOOGLEPLUS")
                //{
                //    bool result = SocialMediaAuthentication.CheckGooglePlusAccessToken("eyJhbGciOiJSUzI1NiIsImtpZCI6Ijk2MmM2NTc0MjVhNGE3YWE0ZGFhM2FiNGNlNjU0NWZhOGM0ZTAxYmYifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiYXVkIjoiMTAzNjE4MjAxODU4OS1xcTVlNDlhNzNzYzRwMHE5ZjAyaXNmaW41NnNuYmNzZC5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjExNzg4NzA0NTM3ODc4ODY4NTMyOCIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhenAiOiIxMDM2MTgyMDE4NTg5LWtxMjZmMnFpM2dhZGlvMWFnZ3QwcWFvYzEzZ3Z2NjQ2LmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJ6bml0ZXI4MUBnbWFpbC5jb20iLCJpYXQiOjE0NDYxNzcxMDgsImV4cCI6MTQ0NjE4MDcwOCwibmFtZSI6IktpYW4gU2VuZyIsInBpY3R1cmUiOiJodHRwczovL2xoNi5nb29nbGV1c2VyY29udGVudC5jb20vLWNKRVp5aUk5N05VL0FBQUFBQUFBQUFJL0FBQUFBQUFBQnkwLzdGU2dMYmIxd21ZL3M5Ni1jL3Bob3RvLmpwZyIsImdpdmVuX25hbWUiOiJLaWFuIiwiZmFtaWx5X25hbWUiOiJTZW5nIn0.Ja-18lzCKorBORYExsjLcZpjhgMzYKLB4Vx9QCzyEt1dqPlg7uzAVmqy0O6i3CzKB2i5bt6jCarBTh5Vnt4OdaVjeDyqAu1sz1v9r6VBCzqmtgDsJa1HLs_NZUK19uLPIIIPobAlAcryPGIDBsnIoDe0sVcs57dkbZXjpohnc8M8nnPNrYkFMQaG1yEuz8MwbgoXRqEKjt0gCetavSU2stAR21QrC4ojfXeAcF1EHvrZgv3UceejtI5Qu3ytajc2YYPCvRcPX6iE5JJUz4sHIu0GMfG-fri5CLgP9PkgpH36-uJpo14gqFMSeg21yXBJnQBhCDmrc4MLm0-I-w9E_g");

                //}

                return(Request.CreateResponse(HttpStatusCode.BadRequest, new CustomResponseMessage()
                {
                    StatusCode = (int)HttpStatusCode.BadRequest, Description = "Invalid UserID/Password"
                }));
            }
        }
        public ActionResult Create([Bind(Include = "Id,UserName,Password,FullName")] ApplicationUser applicationUser)
        {
            if (ModelState.IsValid)
            {
                CustomPasswordHasher customPasswordHasher = new CustomPasswordHasher();
                string hashedPassword = customPasswordHasher.HashPassword(applicationUser.Password);
                applicationUser.Password = hashedPassword;

                db.ApplicationUsers.Add(applicationUser);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(applicationUser));
        }
Пример #12
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var hasher = new CustomPasswordHasher(1000);

            modelBuilder.Entity <Identity>().HasData(
                new Identity
            {
                Id        = 1,
                Email     = "*****@*****.**",
                Password  = hasher.Hash("admin"),
                FirstName = "admin",
                LastName  = "admin",
                Role      = UserRole.Admin
            }
                );
        }
Пример #13
0
        private async Task <string> LoginUser(string userID, string clearPassword)
        {
            if (string.IsNullOrEmpty(clearPassword))
            {
                clearPassword = string.Empty;
            }

            UserTest user = await _serviceUserTest.GetByIDAsync(userID).ConfigureAwait(false);// lstUser.SingleOrDefault(x => x.Code == userID);

            //Xác thực User, nếu chưa đăng ký thì trả về false
            if (user == null || !CustomPasswordHasher.VerifyPassword(user.Password, clearPassword))
            {
                return(string.Empty);
            }
            return(GenerateToken(user));
        }
        public IActionResult RegisterUser(RegistrationModel model)
        {
            var hasher   = new CustomPasswordHasher(1000);
            var identity = new Identity
            {
                Email     = model.Email,
                Password  = hasher.Hash(model.Password),
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Role      = UserRole.Customer
            };

            _databaseContext.Identities.Add(identity);
            _databaseContext.SaveChanges();

            return(Ok(new { status = 200, message = "Account is successfuly created!" }));
        }
        public IActionResult RegisterUser(RegistrationModel model)
        {
            var hasher   = new CustomPasswordHasher(1000);
            var identity = new Identity
            {
                Email     = model.Email,
                Password  = hasher.Hash(model.Password),
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Role      = UserRole.Customer
            };

            _databaseContext.Identities.Add(identity);
            _databaseContext.SaveChanges();

            return(Ok());
        }
Пример #16
0
        public async Task <ActionResult> Index(UserLoginModel userLoginModel)
        {
            if (ModelState.IsValid)
            {
                var user = await db.ApplicationUsers
                           .AsNoTracking()
                           .Where(a => a.UserName.ToUpper() == userLoginModel.UserName.ToUpper())
                           .FirstOrDefaultAsync()
                           .ConfigureAwait(false);

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "Invalid User.");
                    return(View(userLoginModel));
                }

                CustomPasswordHasher customPasswordHasher = new CustomPasswordHasher();

                if (!customPasswordHasher.VerifyPassword(user.Password, userLoginModel.Password))
                {
                    ModelState.AddModelError(string.Empty, "Invalid Password.");
                    return(View(userLoginModel));
                }

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim("FullName", user.FullName)
                };

                var claimsIdentity = new ClaimsIdentity(claims, "ApplicationCookie");

                var context     = Request.GetOwinContext();
                var authManager = context.Authentication;

                authManager.SignIn(new AuthenticationProperties {
                    IsPersistent = false
                }, claimsIdentity);

                return(RedirectToAction("Index", "Home"));
            }

            return(View(userLoginModel));
        }
Пример #17
0
        public async Task <ActionResult <UserTest> > Post([FromBody] UserTest data)
        {
            try
            {
                data.Code = data.Code.ToLower().Trim();
                if (!String.IsNullOrEmpty(data.Email))
                {
                    data.Email = data.Email.ToLower()?.Trim();
                }
                data.Password  = CustomPasswordHasher.HashPassword(data.Password);
                data.CreatedOn = DateTime.Now;
                //data.CreatedBy = UserClaim.UserId;

                return(await _serviceUserTest.InsertAsync(data));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        private ClaimsIdentity GetIdentity(string username, string password)
        {
            var hasher = new CustomPasswordHasher(1000);

            var identity = _databaseContext.Identities.FirstOrDefault(x => x.Email == username);

            if (identity != null && hasher.Check(identity.Password, password).Verified)
            {
                var claims = new List <Claim>
                {
                    new Claim(ClaimsIdentity.DefaultNameClaimType, identity.Id.ToString()),
                    new Claim(ClaimsIdentity.DefaultRoleClaimType, identity.Role.GetString())
                };
                ClaimsIdentity claimsIdentity =
                    new ClaimsIdentity(claims, "Token", ClaimsIdentity.DefaultNameClaimType,
                                       ClaimsIdentity.DefaultRoleClaimType);
                return(claimsIdentity);
            }

            return(null);
        }
        public HttpResponseMessage RegisterNewUser(string LoginType, string UserName, string Name, string ProfilePictureURL, string Password, string MobilePlatform, string PushNotificationID,
                                                   string Country, string Region, string City)
        {
            PenYourPrayerUser user = new PenYourPrayerUser();

            user.LoginType          = LoginType;
            user.UserName           = UserName.Trim();
            user.DisplayName        = Name.Trim();
            user.ProfilePictureURL  = ProfilePictureURL;
            user.Password           = CustomPasswordHasher.HashPassword(Password);
            user.MobilePlatform     = MobilePlatform;
            user.PushNotificationID = PushNotificationID;
            user.City    = City;
            user.Region  = Region;
            user.Country = Country;

            using (DBDataContext db = new DBDataContext())
            {
                string result           = "";
                string HMACSecretKey    = CustomPasswordHasher.HashPassword(Guid.NewGuid().ToString()) + CustomPasswordHasher.HashPassword(Guid.NewGuid().ToString());
                long?  id               = -1;
                string verificationCode = "";
                db.usp_AddNewUser(user.LoginType, user.UserName, user.DisplayName, user.ProfilePictureURL, user.Password, user.MobilePlatform, user.PushNotificationID, HMACSecretKey, user.Country, user.Region, user.City, ref result, ref id, ref verificationCode);
                user.ID = (long)id;

                if (result.ToUpper() != "OK")
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, new CustomResponseMessage()
                    {
                        StatusCode = (int)HttpStatusCode.BadRequest, Description = result
                    }));
                }
                //send email to verify email address.
                CommonMethod.sendAccountActiviationEmail(user.UserName, user.DisplayName, verificationCode, user.ID.ToString());
                return(Request.CreateResponse(HttpStatusCode.OK, new CustomResponseMessage()
                {
                    StatusCode = (int)HttpStatusCode.OK
                }));
            }
        }
        public IActionResult Login([FromBody] MemberDTO user)
        {
            CustomPasswordHasher ph = new CustomPasswordHasher();

            if (user == null)
            {
                return(BadRequest("Invalid client request"));
            }
            //Lookup user by given username
            MemberDTO DbUser = MembersManager.GetMemberByUsername(user.Username);

            if (DbUser != null)
            {
                //Check if given password matches
                if (ph.VerifyHashedPassword(DbUser.PasswordHash, user.Password, DbUser.PasswordSalt) == PasswordVerificationResult.Success)
                {
                    //Create token
                    var secretKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("keycryptstring123"));
                    var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                    var tokeOptions = new JwtSecurityToken(
                        issuer: "https://localhost:44398",
                        audience: "https://localhost:44398",
                        claims: new List <Claim>(),
                        expires: DateTime.Now.AddMinutes(5),
                        signingCredentials: signinCredentials
                        );

                    var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                    return(Ok(new { Token = tokenString }));
                }
                else
                {
                    return(Unauthorized());
                }
            }
            return(NotFound());
        }
Пример #21
0
        //Login lan dau
        public bool IsValidUser(UserAuthen user, bool isLogined)
        {
            //Check User
            bool isValid = false;
            string cacheKey = GetCacheKey(user.UserName);
            if (CacheUser.Contain(cacheKey))
            {
                var uc = CacheUser.Get<User>(cacheKey);

                if (isLogined)
                {
                    //Fast check
                    isValid = uc.PasswordHash == user.PasswordHash;
                }
                else
                {
                    //Very slow
                    var passHash = new CustomPasswordHasher();
                    isValid = passHash.VerifyHashedPassword(uc.PasswordHash, user.Password) == PasswordVerificationResult.Success;
                    if (isValid)
                        user.PasswordHash = uc.PasswordHash;
                }
            }
            else
            {
                //Check User
                var userDB = UserManager.Find(user.UserName, user.Password);
                //Check User
                if (userDB != null)
                {
                    SetUserToCache(userDB, cacheKey);
                    user.PasswordHash = userDB.PasswordHash;
                    isValid = true;
                }
            }
            return isValid;
        }
Пример #22
0
 // *** ADD INT TYPE ARGUMENT TO CONSTRUCTOR CALL:
 public ApplicationUserManager(IUserStore <ApplicationUser, int> store)
     : base(store)
 {
     // Using my custom password hasher function
     PasswordHasher = new CustomPasswordHasher();
 }
Пример #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="SiteId"></param>
        public bool IsAuthenticatedMemberWithCredential(string UserName, string Password, int SiteId)
        {
            string hashPassword = CustomPasswordHasher.HashPassword(Password);

            return(db.Users.Any(m => m.UserName == UserName && m.PasswordHash == hashPassword));
        }
Пример #24
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="objUser"></param>
 /// <returns></returns>
 public async Task CreateWifiUser(User objUser)
 {
     string Password = CustomPasswordHasher.HashPassword(objUser.PasswordHash);
     await UserManager.CreateAsync(objUser, Password);
 }
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "CarMakes",
                columns: table => new
            {
                MakeId = table.Column <int>(nullable: false)
                         .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Make        = table.Column <string>(nullable: true),
                CountryCode = table.Column <string>(nullable: true)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_CarMakes", x => x.MakeId);
            });

            migrationBuilder.CreateTable(
                name: "Clubs",
                columns: table => new
            {
                ClubId = table.Column <int>(nullable: false)
                         .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Name        = table.Column <string>(nullable: true),
                Description = table.Column <string>(nullable: true),
                Photo       = table.Column <string>(nullable: true),
                Contact     = table.Column <string>(nullable: false)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_Clubs", x => x.ClubId);
            });

            migrationBuilder.CreateTable(
                name: "EventTypes",
                columns: table => new
            {
                EventTypeId = table.Column <int>(nullable: false)
                              .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Type = table.Column <int>(nullable: false)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_EventTypes", x => x.EventTypeId);
            });

            migrationBuilder.CreateTable(
                name: "Lowerings",
                columns: table => new
            {
                LoweringId = table.Column <int>(nullable: false)
                             .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Type = table.Column <int>(nullable: false)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_Lowerings", x => x.LoweringId);
            });

            migrationBuilder.CreateTable(
                name: "Events",
                columns: table => new
            {
                EventId = table.Column <int>(nullable: false)
                          .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Name        = table.Column <string>(nullable: false),
                Description = table.Column <string>(nullable: false),
                Location    = table.Column <string>(nullable: false),
                Capacity    = table.Column <int>(nullable: false),
                EventTypeId = table.Column <int>(nullable: false)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_Events", x => x.EventId);
                table.ForeignKey(
                    name: "FK_Events_EventTypes_EventTypeId",
                    column: x => x.EventTypeId,
                    principalTable: "EventTypes",
                    principalColumn: "EventTypeId",
                    onDelete: ReferentialAction.Cascade);
            });

            migrationBuilder.CreateTable(
                name: "Cars",
                columns: table => new
            {
                CarId = table.Column <int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                MakeId         = table.Column <int>(nullable: false),
                Model          = table.Column <string>(nullable: true),
                ProductionYear = table.Column <int>(nullable: false),
                Displacement   = table.Column <string>(nullable: true),
                LoweringId     = table.Column <int>(nullable: false),
                Wheels         = table.Column <string>(nullable: true),
                MemberId       = table.Column <int>(nullable: false)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_Cars", x => x.CarId);
                table.ForeignKey(
                    name: "FK_Cars_Lowerings_LoweringId",
                    column: x => x.LoweringId,
                    principalTable: "Lowerings",
                    principalColumn: "LoweringId",
                    onDelete: ReferentialAction.Cascade);
                table.ForeignKey(
                    name: "FK_Cars_CarMakes_MakeId",
                    column: x => x.MakeId,
                    principalTable: "CarMakes",
                    principalColumn: "MakeId",
                    onDelete: ReferentialAction.Cascade);
            });

            migrationBuilder.CreateTable(
                name: "Members",
                columns: table => new
            {
                MemberId = table.Column <int>(nullable: false)
                           .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                Name         = table.Column <string>(nullable: false),
                Surname      = table.Column <string>(nullable: false),
                DateOfBirth  = table.Column <DateTime>(nullable: false),
                PostalCode   = table.Column <string>(nullable: false),
                City         = table.Column <string>(nullable: false),
                Email        = table.Column <string>(nullable: false),
                Username     = table.Column <string>(nullable: false),
                PasswordHash = table.Column <string>(nullable: true),
                PasswordSalt = table.Column <string>(nullable: true),
                CarId        = table.Column <int>(nullable: false),
                ClubId       = table.Column <int>(nullable: false),
                CarId1       = table.Column <int>(nullable: true)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_Members", x => x.MemberId);
                table.ForeignKey(
                    name: "FK_Members_Cars_CarId1",
                    column: x => x.CarId1,
                    principalTable: "Cars",
                    principalColumn: "CarId",
                    onDelete: ReferentialAction.Restrict);
                table.ForeignKey(
                    name: "FK_Members_Clubs_ClubId",
                    column: x => x.ClubId,
                    principalTable: "Clubs",
                    principalColumn: "ClubId",
                    onDelete: ReferentialAction.Cascade);
            });

            migrationBuilder.CreateTable(
                name: "Registrations",
                columns: table => new
            {
                RegistrationId = table.Column <int>(nullable: false)
                                 .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                MemberId = table.Column <int>(nullable: false),
                EventId  = table.Column <int>(nullable: false)
            },
                constraints: table =>
            {
                table.PrimaryKey("PK_Registrations", x => x.RegistrationId);
                table.ForeignKey(
                    name: "FK_Registrations_Events_EventId",
                    column: x => x.EventId,
                    principalTable: "Events",
                    principalColumn: "EventId",
                    onDelete: ReferentialAction.Cascade);
                table.ForeignKey(
                    name: "FK_Registrations_Members_MemberId",
                    column: x => x.MemberId,
                    principalTable: "Members",
                    principalColumn: "MemberId",
                    onDelete: ReferentialAction.Cascade);
            });

            migrationBuilder.CreateIndex(
                name: "IX_Cars_LoweringId",
                table: "Cars",
                column: "LoweringId");

            migrationBuilder.CreateIndex(
                name: "IX_Cars_MakeId",
                table: "Cars",
                column: "MakeId");

            migrationBuilder.CreateIndex(
                name: "IX_Events_EventTypeId",
                table: "Events",
                column: "EventTypeId");

            migrationBuilder.CreateIndex(
                name: "IX_Members_CarId1",
                table: "Members",
                column: "CarId1");

            migrationBuilder.CreateIndex(
                name: "IX_Members_ClubId",
                table: "Members",
                column: "ClubId");

            migrationBuilder.CreateIndex(
                name: "IX_Registrations_EventId",
                table: "Registrations",
                column: "EventId");

            migrationBuilder.CreateIndex(
                name: "IX_Registrations_MemberId",
                table: "Registrations",
                column: "MemberId");


            //EventTypes
            migrationBuilder.InsertData(
                table: "EventTypes",
                columns: new[] { "EventTypeId", "Type" },
                values: new object[] { 1, 1 });
            migrationBuilder.InsertData(
                table: "EventTypes",
                columns: new[] { "EventTypeId", "Type" },
                values: new object[] { 2, 2 });
            migrationBuilder.InsertData(
                table: "EventTypes",
                columns: new[] { "EventTypeId", "Type" },
                values: new object[] { 3, 3 });
            migrationBuilder.InsertData(
                table: "EventTypes",
                columns: new[] { "EventTypeId", "Type" },
                values: new object[] { 4, 4 });
            migrationBuilder.InsertData(
                table: "EventTypes",
                columns: new[] { "EventTypeId", "Type" },
                values: new object[] { 5, 5 });

            //Lowerings
            migrationBuilder.InsertData(
                table: "Lowerings",
                columns: new[] { "LoweringId", "Type" },
                values: new object[] { 1, 1 });
            migrationBuilder.InsertData(
                table: "Lowerings",
                columns: new[] { "LoweringId", "Type" },
                values: new object[] { 2, 2 });
            migrationBuilder.InsertData(
                table: "Lowerings",
                columns: new[] { "LoweringId", "Type" },
                values: new object[] { 3, 3 });
            migrationBuilder.InsertData(
                table: "Lowerings",
                columns: new[] { "LoweringId", "Type" },
                values: new object[] { 4, 4 });

            //CarMakes
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 1, "BMW", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 2, "Audi", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 3, "Mercedes", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 4, "Porsche", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 5, "Volkswagen", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 6, "Opel", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 7, "Mazda", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 8, "Mitsubishi", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 9, "Honda", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 10, "Subaru", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 11, "Toyota", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 12, "Suzuki", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 13, "Nissan", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 14, "Daihatsu", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 15, "Abarth", "ITA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 16, "AC", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 17, "Acura", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 18, "Alfa Romeo", "ITA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 19, "Aston Martin", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 20, "Bently", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 21, "Bugatti", "FRA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 22, "Buick", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 23, "Cadillac", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 24, "Chevrolet", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 25, "Citroën", "FRA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 26, "Chrysler", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 27, "Datsun", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 28, "Dodge", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 29, "Ferrari", "ITA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 30, "Fiat", "ITA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 31, "Ford", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 32, "Genesis", "KOR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 33, "GMC", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 34, "Holden", "AUS" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 35, "Hyundai", "KOR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 36, "Infinity", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 37, "Jaguar", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 38, "Jeep", "ITA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 39, "Koenigsegg", "SWE" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 40, "Kia", "KOR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 41, "Lamborghini", "ITA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 42, "Land Rover", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 43, "Lexus", "JAP" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 44, "Lincoln", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 45, "Lotus", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 46, "Maserati", "ITA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 47, "McLaren", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 48, "MG", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 49, "Mini", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 50, "Peugot", "FRA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 51, "Plymouth", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 52, "Renault", "FRA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 53, "Rolls-Royce", "GBR" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 54, "Seat", "SPA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 55, "Smart", "GER" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 56, "Tesla", "USA" });
            migrationBuilder.InsertData(
                table: "CarMakes",
                columns: new[] { "MakeID", "Make", "CountryCode" },
                values: new object[] { 57, "Volvo", "SWE" });
            //Cars
            migrationBuilder.InsertData(
                table: "Cars",
                columns: new[] { "CarId", "MakeId", "Model", "ProductionYear", "Displacement", "LoweringId", "Wheels", "MemberId" },
                values: new object[] { 1, 7, "3",
                                       "2015", "2000 cc", 3,
                                       "asa TEC GT7 19\"", 1 });

            //Clubs
            migrationBuilder.InsertData(
                table: "Clubs",
                columns: new[] { "ClubId", "Name", "Description", "Photo", "Contact" },
                values: new object[] { 1, "MazdaClubBelgium", "Club uit België, alle modellen binnen mazda zijn toegelaten.",
                                       "no photo", "*****@*****.**" });
            migrationBuilder.InsertData(
                table: "Clubs",
                columns: new[] { "ClubId", "Name", "Description", "Photo", "Contact" },
                values: new object[] { 2, "DuitseOldtimer", "Club voor duitse oldtimers.", "no photo", "*****@*****.**" });

            //Members
            CustomPasswordHasher ph = new CustomPasswordHasher();

            string salt = ph.GetSalt();

            migrationBuilder.InsertData(
                table: "Members",
                columns: new[] { "MemberId", "Name", "Surname", "DateOfBirth", "PostalCode", "City", "Email", "Username", "PasswordHash", "PasswordSalt", "CarId", "ClubId" },
                values: new object[] { 1, "Gert", "Scheers",
                                       DateTime.Parse("1994-11-17").Date, "3920", "Lommel",
                                       "*****@*****.**", "gert.scheers", ph.HashPassword("test", salt), salt, 1, 1 });
            //REDO ph.GetSalt() for every new user to create different salts

            //Events
            migrationBuilder.InsertData(
                table: "Events",
                columns: new[] { "EventId", "Name", "Description", "Location", "Capacity", "EventTypeId" },
                values: new object[] { 1, "Japfest", "Meeting op Circuit Zandvoort, enkel voor Japanse auto's en brommers.",
                                       "Zandvoort", 1500, 1 });
            migrationBuilder.InsertData(
                table: "Events",
                columns: new[] { "EventId", "Name", "Description", "Location", "Capacity", "EventTypeId" },
                values: new object[] { 2, "Germanized", "Meeting voor Duitse merken.", "Hechtel", 500, 2 });
        }
Пример #26
0
 public UserService(IMapper mapper, DataContext context)
 {
     _mapper              = mapper;
     _context             = context;
     customPasswordHasher = new CustomPasswordHasher();
 }
Пример #27
0
        public IActionResult Login(AccountLogin user)
        {
            using (GlobalDBContext _context = new GlobalDBContext())
            {
                //var userA = _context.Users.ToList<User>();
                User theUser = _context.Users.Include(p => p.Role).FirstOrDefault(u => u.UserEmail == user.Email);
                // Check if the user with email exists
                if (theUser != null)
                {
                    //Check email is verified
                    if (theUser.UserEmailVerified == false)
                    {
                        ModelState.AddModelError("", "Email is not verifed you cant login.");
                        return(View());
                    }
                    CustomPasswordHasher pwd = new CustomPasswordHasher();
                    string hashed            = pwd.HashPassword(user.Password, theUser.Salt);
                    // Check if the user entered password is correct
                    if (hashed == theUser.UserPassword)
                    {
                        //string usr = JsonConvert.SerializeObject(theUser, Formatting.Indented, new JsonSerializerSettings()
                        //{
                        //    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        //});

                        // Custom Auth Token

                        var token = _auth.Authenticate(theUser.UserEmail, theUser.Role.RoleName, theUser.UserId);
                        // Create Sessions
                        //HttpContext.Session.SetString("UserSession", usr);
                        HttpContext.Session.SetString("UserToken", token);

                        // Delete Existing cookie
                        Response.Cookies.Delete("UserToken");
                        //Create Cookie
                        if (user.RememberMe)
                        {
                            CookieOptions cookieOptions = new CookieOptions();
                            cookieOptions.Expires = DateTime.Now.AddDays(7);
                            Response.Cookies.Append("UserToken", token, cookieOptions);
                        }

                        // at Genearted token in header
                        using (var client = new HttpClient())
                        {
                            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                        }
                        if (TempData.ContainsKey("redirect"))
                        {
                            string redirectUrl = TempData["redirect"].ToString();
                            string fullPath    = host + "/" + redirectUrl;
                            return(Redirect(fullPath));
                        }

                        // Id 1 for Student & Id 2 for Employer
                        if (theUser.Role.RoleId == 1)
                        {
                            // Student
                            return(RedirectToAction("Index", "DashboardStudent"));
                        }
                        if (theUser.Role.RoleId == 2)
                        {
                            // Employer
                            return(RedirectToAction("Index", "DashboardEmployer"));
                        }
                        if (theUser.Role.RoleId == 3)
                        {
                            // Teacher
                            return(RedirectToAction("Index", "DashboardTeacher"));
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Wrong Credentials.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "No user exists with the given email.");
                    ModelState.AddModelError("", "Wrong Credentials.");
                }

                return(View());
            }
        }
 public ApplicationUserManager(IUserStore <ApplicationUser> store)
     : base(store)
 {
     PasswordHasher = new CustomPasswordHasher();
 }
Пример #29
0
        public IActionResult Login([FromBody] LoginViewModel model)
        {
            if (model == null)
            {
                return(Unauthorized(new { ErrorMessage = "Login failed.Please enter your password and username." }));
            }

            var user = _userService.GetUserByUsername(model.Username);

            if (user == null)
            {
                return(Unauthorized(new { ErrorMessage = "Login failed.Invalid username has entered." }));
            }
            else
            {
                var passwordHash = CustomPasswordHasher.GenerateHash(model.Password);

                if (user.Password == passwordHash)
                {
                    var test      = _config["Tokens:Key"];
                    var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
                    //var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(comapny.SecretKey.ToString()));
                    var    signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
                    string userRole          = string.Empty;
                    string roles             = string.Join(",", user.UserRoles.Select(t => t.Role.Name).ToList());

                    var      now     = DateTime.UtcNow;
                    DateTime nowDate = DateTime.UtcNow;
                    var      claims  = new[]
                    {
                        new Claim(JwtRegisteredClaimNames.Sub, user.Username),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(), ClaimValueTypes.Integer64),
                        new Claim(JwtRegisteredClaimNames.Aud, "admin"),
                        new Claim(ClaimTypes.Role, roles)
                    };


                    var tokenOptions = new JwtSecurityToken(
                        issuer: _config["Tokens:Issuer"],
                        claims: claims,
                        notBefore: nowDate,
                        expires: nowDate.AddDays(100),
                        signingCredentials: signinCredentials

                        );

                    var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                    return(Ok(new
                    {
                        Token = tokenString,
                        FirstName = user.FirstName,
                        Email = user.Email,
                        ProfilePic = "",
                        Role = user.UserRoles.FirstOrDefault().Role.Name
                    }));
                }
                else
                {
                    return(Unauthorized(new { ErrorMessage = "Login failed.Invalid password has entered." }));
                }
            }
        }
        public HttpResponseMessage SocialLogin(string LoginType, string UserName, string Secret, string AccessToken, string PushNotificationID, string MobilePlatform)
        {
            bool              socialresult = false;
            object            token        = null;
            PenYourPrayerUser tuser        = new PenYourPrayerUser();

            if (LoginType.ToUpper() == "FACEBOOK")
            {
                socialresult = SocialMediaAuthentication.CheckFacebookAccessToken(AccessToken, ref token);
                if (socialresult)
                {
                    FacebookDebugToken fbtoken = (FacebookDebugToken)token;
                    tuser.ProfilePictureURL = fbtoken.data.usertoken.picture.data.url;
                    tuser.DisplayName       = fbtoken.data.usertoken.name;
                    tuser.UserName          = fbtoken.data.usertoken.email;
                }
            }
            //else if (LoginType.ToUpper() == "TWITTER")
            //{
            //    result = SocialMediaAuthentication.checkTwitterAccessToken(UserName, "806837785-trTr0ObdqaW0owy1N0WXJFh6OGSlgUH74nh3qoHO", "w5j7WPwHWwY4DSfJ82tRVZF7SBogZJ6XABptVt431uOowvwFKC");
            //}
            else if (LoginType.ToUpper() == "GOOGLEPLUS")
            {
                socialresult = SocialMediaAuthentication.CheckGooglePlusAccessToken(AccessToken, ref token);
                if (socialresult)
                {
                    GoogleTokenInfo gptoken = (GoogleTokenInfo)token;
                    tuser.ProfilePictureURL = gptoken.picture;
                    tuser.DisplayName       = gptoken.name;
                    tuser.UserName          = gptoken.email;
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new CustomResponseMessage()
                {
                    StatusCode = (int)HttpStatusCode.BadRequest, Description = "Invalid Social Login"
                }));
            }


            if (!socialresult)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new CustomResponseMessage()
                {
                    StatusCode = (int)HttpStatusCode.BadRequest, Description = "Invalid Social Login"
                }));
            }
            else
            {
                using (DBDataContext db = new DBDataContext())
                {
                    PenYourPrayerUser user;
                    List <usp_GetUserInformationResult> res = db.usp_GetUserInformation(LoginType, UserName).ToList();
                    if (res.Count() > 0)
                    {
                        usp_GetUserInformationResult t = res.ElementAt(0);
                        db.usp_UpdateUserMobileDeviceInformation(t.ID, MobilePlatform, PushNotificationID);
                        db.usp_UpdateUserSocialInformation(t.ID, tuser.DisplayName, tuser.UserName, tuser.ProfilePictureURL);

                        user                    = new PenYourPrayerUser();
                        user.ID                 = t.ID;
                        user.DisplayName        = tuser.DisplayName;
                        user.LoginType          = t.LoginType;
                        user.UserName           = t.UserName;
                        user.MobilePlatform     = MobilePlatform;
                        user.ProfilePictureURL  = tuser.ProfilePictureURL;
                        user.PushNotificationID = PushNotificationID;
                        user.HMACHashKey        = t.HMACHashKey;
                        user.EmailVerification  = true;
                    }
                    else
                    {
                        //create new account
                        string result           = "";
                        string verificationCode = "";
                        long?  id            = -1;
                        string HMACSecretKey = CustomPasswordHasher.HashPassword(Guid.NewGuid().ToString()) + CustomPasswordHasher.HashPassword(Guid.NewGuid().ToString());
                        db.usp_AddNewUser(LoginType, UserName, tuser.DisplayName, tuser.ProfilePictureURL, "", MobilePlatform, PushNotificationID, HMACSecretKey, null, null, null, ref result, ref id, ref verificationCode);

                        user                    = new PenYourPrayerUser();
                        user.ID                 = (long)id;
                        user.DisplayName        = tuser.DisplayName;
                        user.LoginType          = LoginType;
                        user.UserName           = UserName;
                        user.MobilePlatform     = MobilePlatform;
                        user.ProfilePictureURL  = tuser.ProfilePictureURL;
                        user.PushNotificationID = PushNotificationID;
                        user.HMACHashKey        = HMACSecretKey;
                        user.EmailVerification  = true;
                    }
                    return(Request.CreateResponse(HttpStatusCode.OK, user));
                }
            }
        }
Пример #31
0
 public AuthRepository(DataContext context, IJwtAuthManager jwtAuthManager)
 {
     _context             = context;
     customPasswordHasher = new CustomPasswordHasher();
     _jwtAuthManager      = jwtAuthManager;
 }