public async Task <HttpResponseMessage> Login(LoginUserModel model)
        {
            var content = new StringContent(JsonConvert.SerializeObject(model));

            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            var response = await api.Post(ApiEndpoints.UserLogin, content);

            //If login is unsuccessful do not set cookie
            if (!response.IsSuccessStatusCode)
            {
                return(response);
            }

            return(response);
        }
Exemplo n.º 2
0
        public HttpResponse Login(LoginUserModel model)
        {
            var userId = this.context.Users.Where(u => u.UserName == model.Username &&
                                                  u.Password == hasher.ComputeSha256Hash(model.Password))
                         .Select(u => u.Id)
                         .FirstOrDefault();

            if (userId == null)
            {
                return(Error("This user is not registrated."));
            }
            this.SignIn(userId);

            return(Redirect("/Repositories/All"));
        }
Exemplo n.º 3
0
        public UserModel Login(LoginUserModel model)
        {
            using (var dbContext = new MissionskyOAEntities())
            {
                string pwd  = Cryptology.Encrypt(model.Password);
                var    user =
                    dbContext.Users.Where(it => it.Email == model.UserName && it.Password == pwd).FirstOrDefault();
                if (user != null)
                {
                    return(user.ToModel());
                }
            }

            return(null);
        }
Exemplo n.º 4
0
        public ActionResult ForgotPassword([Bind(Exclude = "Password,RememberMe")] LoginUserModel model)
        {
            ModelState.Remove("Password");
            ModelState.Remove("RememberMe");

            if (ModelState.IsValid)
            {
                var isSendResetPasswordCode = _userModel.SendResetPasswordCode(model);
                if (isSendResetPasswordCode)
                {
                    return(RedirectToAction("Login"));
                }
            }
            return(View(model));
        }
Exemplo n.º 5
0
        private UserViewModel AuthenticateUser(LoginUserModel login)
        {
            var user = mediator.Send(new GetUserByEmailAddressRequest {
                EmailAddress = login.Email
            }).Result;

            var isPasswordVerified = PasswordEncrypter.VerifyPassword(login.Password, user.EncryptedPassword);

            if (isPasswordVerified)
            {
                return(user);
            }

            return(null);
        }
Exemplo n.º 6
0
        public async Task <UserReturnModel> Login([FromBody] LoginUserModel creds)
        {
            if (ModelState.IsValid)
            {
                UserReturnModel user = _db.Login(creds);
                if (user != null)
                {
                    ClaimsPrincipal principal = user.SetClaims();
                    await HttpContext.SignInAsync(principal);

                    return(user);
                }
            }
            return(null);
        }
Exemplo n.º 7
0
        public static LoginUserModel ExctractClaims(this ClaimsPrincipal userClaims)
        {
            var username = userClaims.Claims.FirstOrDefault(t => t.Type == ClaimTypes.Name)?.Value;
            var role     = userClaims.Claims.FirstOrDefault(t => t.Type == ClaimTypes.Role)?.Value;
            var userId   = userClaims.Claims.FirstOrDefault(t => t.Type == ClaimTypes.Sid)?.Value;

            var user = new LoginUserModel
            {
                Id = int.Parse(userId), Username = username, Information = new UserInformation {
                    Role = role
                }
            };

            return(user);
        }
 public JsonResult loginUser(LoginUserModel loginUser)
 {
     if (ModelState.IsValid)
     {
         LoginManager _loginM = new LoginManager();
         var          result  = _loginM.LoginUser(loginUser);
         return(Json(result, JsonRequestBehavior.AllowGet));
     }
     else
     {
         return(Json(new ResponseModel {
             IsSuccess = false, Message = "Bilgileri kontrol ediniz!"
         }));
     }
 }
Exemplo n.º 9
0
 public ActionResult Login(LoginUserModel user)
 {
     if (ModelState.IsValid)
     {
         if (membershipProvider.ValidateUser(user.Username, user.Password))
         {
             FormsAuthentication.SetAuthCookie(user.Username, !user.NotRememberMe);
             return(RedirectToAction("Index", "Home"));
         }
         {
             ModelState.AddModelError("LoginResult", "Неверный логин или пароль");
         }
     }
     return(View(user));
 }
Exemplo n.º 10
0
        public async Task <ActionResult> Create(RegUserModel user)
        {
            var response = await service.RegisterUser(user);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                UserModel userCreated = new UserModel();
                userCreated.UserName    = user.UserName;
                userCreated.Email       = user.Email;
                userCreated.PhoneNumber = user.PhoneNumber;

                //Log user in
                LoginUserModel login = new LoginUserModel();
                login.UserName = user.UserName;
                login.Password = user.Password;
                IList <string> tokenIn = await loginService.GenerateToken(login);

                if (tokenIn == null)
                {
                    return(View("Success", userCreated));
                }
                System.Web.HttpContext.Current.Response.Cookies.Add(new HttpCookie("AccessToken")
                {
                    Value    = tokenIn[0],
                    HttpOnly = true,
                    Expires  = DateTime.Now.AddSeconds(Convert.ToDouble(tokenIn[1])) //TODO: Tokens now expire in UTC time
                });

                System.Web.HttpContext.Current.Session["AccessToken"] = tokenIn[0];

                System.Web.HttpContext.Current.Response.Cookies.Add(new HttpCookie("UserName")
                {
                    Value    = user.UserName,
                    HttpOnly = true,
                    Expires  = DateTime.Now.AddSeconds(Convert.ToDouble(tokenIn[1])) //TODO: Tokens now expire in UTC time
                });

                System.Web.HttpContext.Current.Session["UserName"] = user.UserName;

                return(View("Success", userCreated));
            }
            else
            {
                user.Password        = null;
                user.ConfirmPassword = null;
                return(View("~/Views/Home/Splash.cshtml", user));
            }
        }
Exemplo n.º 11
0
        public async Task <ActionResult> Login(LoginUserModel loginUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values.SelectMany(e => e.Errors)));
            }

            var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true);

            if (result.Succeeded)
            {
                return(Ok(await GenerateJwt(loginUser.Email)));
            }

            return(BadRequest("Invalid user or password"));
        }
Exemplo n.º 12
0
        public async Task <Option <JwtModel, Error> > Login(LoginUserModel model)
        {
            var loginResult = await(await UserManager.FindByEmailAsync(model.Email))
                              .SomeNotNull()
                              .FilterAsync(async user => await UserManager.CheckPasswordAsync(user, model.Password));

            return(loginResult.Match(
                       user =>
            {
                return new JwtModel
                {
                    TokenString = JwtFactory.GenerateEncodedToken(user.Id, user.Email, new List <Claim>())
                }.Some <JwtModel, Error>();
            },
                       () => Option.None <JwtModel, Error>(new Error("Invalid credentials."))));
        }
Exemplo n.º 13
0
        public UserReturnModel Login(LoginUserModel creds)
        {
            User user = _db.QueryFirstOrDefault <User>(@"
            SELECT * FROM users WHERE email = @Email
            ", creds);

            if (user != null)
            {
                var valid = BCrypt.Net.BCrypt.Verify(creds.Password, user.Password);
                if (valid)
                {
                    return(user.GetReturnModel());
                }
            }
            return(null);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> Login([FromBody] LoginUserModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            TokenAuthorizationResult?result = await _authorizationService.Login(model);

            if (result == null)
            {
                return(BadRequest());
            }

            return(Ok(result));
        }
Exemplo n.º 15
0
        public async Task <User> Login(LoginUserModel loginUserModel)
        {
            var user = await DbContext.Users.FirstOrDefaultAsync(x => x.Email == loginUserModel.Email);

            if (user == null)
            {
                return(null);
            }

            if (!VerifyPasswordHash(loginUserModel.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(null);
            }

            return(user);
        }
Exemplo n.º 16
0
        public async Task <ActionResult <UserModel> > AddUser(LoginUserModel newUser)
        {
            var isUserNameTaken = (await this.userRepository.GetUserByUsername(newUser.Username)) != null;

            if (isUserNameTaken)
            {
                return(Conflict("Username is already taken"));
            }

            newUser.Password = this.hashGenerator.GenerateHashFor(newUser.Password);

            var userToAdd = this.mapper.Map <User>(newUser);

            this.userRepository.AddUser(userToAdd);
            return(Created("", this.mapper.Map <UserModel>(userToAdd)));
        }
Exemplo n.º 17
0
        public async Task <IActionResult> Login(LoginUserModel loginUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = await _authService.Login(loginUserModel);

            if (result.Error != null)
            {
                return(Unauthorized(result));
            }

            return(Ok(result));
        }
Exemplo n.º 18
0
        public async Task <IActionResult> Login(LoginUserModel loginRequest)
        {
            if (loginRequest == null || string.IsNullOrEmpty(loginRequest.Username) || string.IsNullOrEmpty(loginRequest.Password))
            {
                return(BadRequest("Missing login details"));
            }

            var loginResponse = await _accountService.Login(loginRequest);

            if (loginResponse == null)
            {
                return(BadRequest($"Invalid credentials"));
            }

            return(Ok(loginResponse));
        }
Exemplo n.º 19
0
        public async Task <IActionResult> Login(LoginUserModel loginRequest)
        {
            if (loginRequest == null || string.IsNullOrEmpty(loginRequest.Username) || string.IsNullOrEmpty(loginRequest.Password))
            {
                return(BadRequest("Missing login details"));
            }

            var loginResponse = await _userService.Login(loginRequest);

            if (loginResponse == null)
            {
                return(Ok(new { status = 104, message = $"The username or password was not correct" }));
            }

            return(Ok(loginResponse));
        }
Exemplo n.º 20
0
        public async Task <IHttpActionResult> Login(LoginUserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            IdentityUser result = await _repo.FindUser(userModel.UserName, userModel.Password);

            if (result == null)
            {
                return(Unauthorized());
            }

            return(Ok());
        }
Exemplo n.º 21
0
        private async void CheckUser()
        {
            var user = new LoginUserModel()
            {
                Email = Email, Password = Password, RememberMe = true
            };
            var result = await server.LoginUser(user);

            if (result == default(MobileUserServer))
            {
                //peta tou popup oti kanei egine alani
                //edw to login einai unsuccesfull
                try
                {
                    await Shell.Current.Navigation.PushPopupAsync(new InfoPopup("Error", "Something went wrong please enter valid credentials!"));
                }
                catch (NullReferenceException ex)
                {
                    await App.Current.MainPage.Navigation.PushPopupAsync(new InfoPopup("Error", "Something went wrong please enter valid credentials!"));
                }
            }
            else
            {
                //successful login!!! kane kati
                if (IsChecked)
                {
                    var user_temp = new MobileUser()
                    {
                        Email = user.Email, Password = user.Password
                    };
                    try
                    {
                        await database.createUser(user_temp);

                        App.CurrentUserEmail = user_temp.Email;
                    }
                    catch (Exception ex)
                    {
                        await App.Current.MainPage.Navigation.PushPopupAsync(new InfoPopup("Error", "Couldnt save user in the localdb!"));
                    }
                }
                App.CurrentUserEmail = user.Email;
                App.Current.MainPage = new AppShell();
            }
            Console.WriteLine("");
            Console.WriteLine("");
        }
Exemplo n.º 22
0
        public async Task <IActionResult> doLogin(LoginViewModel model)
        {
            var parameters = new NameValueCollection();

            parameters.Add("grant_type", "password");
            parameters.Add("username", model.UserName);
            parameters.Add("password", model.Password);
            parameters.Add("client_id", _identityServerClientId);
            parameters.Add("client_secret", _identityServerSecret);

            using (var client = new WebClient())
            {
                try {
                    client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                    string myurl = $"{this.Request.Scheme}://{this.Request.Host}{this.Request.PathBase}";

                    var response_data = client.UploadValues(myurl + "/token",
                                                            "POST",
                                                            parameters);
                    var     ret  = Encoding.UTF8.GetString(response_data);
                    JObject json = JObject.Parse(ret);

                    //user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;
                    var            identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                    LoginUserModel lm       = new LoginUserModel {
                        UserName = model.UserName, Token = (string)json["access_token"]
                    };
                    identity.AddClaim(new Claim(ClaimTypes.Name, JsonHelper.Serialize(lm)));
                    AuthenticationProperties ap = null;
                    if (model.RememberMe)
                    {
                        ap = new AuthenticationProperties
                        {
                            IsPersistent = model.RememberMe,
                            ExpiresUtc   = DateTime.UtcNow.AddDays(1)
                        };
                    }
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), ap);

                    return(RedirectToAction("list", "borrow"));
                }
                catch (Exception x) {
                    return(View("Login"));
                }
            }
        }
        public async Task <IActionResult> LoginAsync([FromBody] LoginUserModel request)
        {
            if (ModelState.IsValid)
            {
                var userInDb = await _context.Users.Where(x => x.EmailAddress == request.EmailAddress && x.Password == request.Password).FirstOrDefaultAsync();

                if (userInDb != null)
                {
                    return(Ok(userInDb));
                }
                else
                {
                    return(NotFound());
                }
            }
            return(BadRequest());
        }
Exemplo n.º 24
0
        public async Task <IActionResult> Login(LoginUserModel loginUserModel)
        {
            // Attempt to log user in
            var userFromDb = await repo.Login(loginUserModel.Username.ToLower(), loginUserModel.Password.ToLower());

            // If return value is null, login failed
            if (userFromDb == null)
            {
                // Avoid giving users hints as to if username exists or password is incorrect, return Unauthorized...
                return(Unauthorized());
            }

            // Start building auth token
            // Create claims
            var claims = new[]
            {
                // Database id claim
                new Claim(ClaimTypes.NameIdentifier, userFromDb.Id.ToString()),

                // Username claim
                new Claim(ClaimTypes.Name, userFromDb.Username)
            };

            // Create security key
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetSection("AppSettings:Token").Value));

            // Create signing credentials to validate the token using encrypted security key
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            // Token descriptor used to create the token
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            // Handler used to create token based on the token descripter
            var tokenHandler = new JwtSecurityTokenHandler();

            // Create actual token
            var token = tokenHandler.CreateToken(tokenDescriptor);

            // return token and OK status
            return(Ok(new { token = tokenHandler.WriteToken(token) }));
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Login(LoginUserModel model)
        {
            try
            {
                var result = await _authService.LoginAsync(model.Email, model.Password);

                return(result.HasValue
                    ? OkJson(result.Value.ToTokenResponse())
                    : Unauthorized());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error during user login! " +
                                 $"User: {model.Email}");
                return(InternalServerErrorJson(ex));
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// 设置用户登录后的session
        /// </summary>
        /// <param name="user"></param>
        public static void SetLoginUserSession(LoginUserModel user)
        {
            var session = HttpContext.Current.Session;

            session[ConstClass.SessionKeyMLoginUser] = user.UserID;

            RedisCacheHelper.Add(GetLoginUserRedisKey(user.UserID), user, DateTime.Now.AddMinutes(session.Timeout));

            if (user.Status == 1)
            {
                CookieHelper.SetCookie(ConstClass.LoginUserCookieKey
                                       , dic: new Dictionary <string, string> {
                    { "username", user.UserName },
                    { "Id", user.UserID.ToString() }
                });
            }
        }
Exemplo n.º 27
0
        public async Task <ActionResult <string> > GetTokenForUser(LoginUserModel user)
        {
            var userFromDatabase = await this.userRepository.GetUserByUsername(user.Username);

            if (userFromDatabase == null)
            {
                return(NotFound());
            }

            if (this.PasswordIsCorrect(user.Password, userFromDatabase.Password))
            {
                var token = this.tokenProvider.GenerateToken(user.Username);
                return(Ok(token));
            }

            return(Unauthorized());
        }
Exemplo n.º 28
0
        public async Task Login_Should_Return_Jwt(LoginUserModel model, User expectedUser, string expectedJwt)
        {
            // Arrange
            MockFindByEmail(model.Email, expectedUser);

            MockCheckPassword(expectedUser, model.Password, true);

            _jwtFactoryMock.Setup(jwtFactory => jwtFactory
                                  .GenerateEncodedToken(expectedUser.Id, expectedUser.Email, new List <Claim>()))
            .Returns(expectedJwt);

            // Act
            var result = await _usersService.Login(model);

            // Assert
            result.Exists(jwt => jwt.TokenString == expectedJwt).ShouldBeTrue();
        }
Exemplo n.º 29
0
        public async Task <IActionResult> Login([FromBody] LoginUserModel user)
        {
            if (ModelState.IsValid)
            {
                var token = await _userServices.Login(_mapper.Map <LoginUserBLL>(user));

                if (token == null)
                {
                    BadRequest();
                }
                return(Ok(token));
            }
            else
            {
                return(BadRequest());
            }
        }
        public Object LoginUser([FromBody] LoginUserModel logUser)
        {
            var currentUser = _context.users.Include(user => user.QuizResults).SingleOrDefault(user => user.Email == logUser.Email);

            if (currentUser == null)
            {
                //SOME ERROR MESSAGE FOR FRONT END
                return(BadRequest("User email does not exist"));
            }
            List <SlimQuizResult> SlimQuizResults = new List <SlimQuizResult>();

            foreach (var OneSlimQuizResult in currentUser.QuizResults)
            {
                SlimQuizResult SlimQuizResult = new SlimQuizResult {
                    QuizResultID = OneSlimQuizResult.QuizResultID,
                    ResultString = OneSlimQuizResult.ResultString,
                    QuizID       = OneSlimQuizResult.QuizID,
                    UserID       = OneSlimQuizResult.UserID
                };
                SlimQuizResults.Add(SlimQuizResult);
            }
            SlimUser NewSlimUser = new SlimUser {
                FirstName    = currentUser.FirstName,
                LastName     = currentUser.LastName,
                ConnectionID = currentUser.ConnectionID,
                UserID       = currentUser.UserID,
                QuizResults  = SlimQuizResults
            };

            //Compare passwords
            // byte[] Salt = Convert.FromBase64String (currentUser.Salt);
            // string HashSaltedPswd = CreatePasswordHash(currentUser.Password, Salt);

            // if (HashSaltedPswd == currentUser.Password){
            if (logUser.Password == currentUser.Password)
            {
                HttpContext.Session.SetObjectAsJson("currentUser", NewSlimUser);
                HttpContext.Session.SetInt32("UserID", currentUser.UserID);
                return(NewSlimUser);
            }
            else
            {
                return(BadRequest("Password does not match!"));
            };
        }