예제 #1
0
        public async Task <ActionResult> Login(UserLoginRequestModel loginRequest, string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = await _userService.ValidateUser(loginRequest.Email, loginRequest.Password);

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

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.Email),
                new Claim(ClaimTypes.GivenName, user.FirstName),
                new Claim(ClaimTypes.Surname, user.LastName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };

            //if (user.Roles != null) claims.AddRange(user.Roles.Select(role => new Claim(ClaimTypes.Role, role.Name)));

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity));

            return(LocalRedirect(returnUrl));
        }
예제 #2
0
        public async Task <IActionResult> Login(UserLoginRequestModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return(Unauthorized("Invalid or missing params"));
            }

            try
            {
                var user = await _userService.ValidateUser(userModel.Email, userModel.Password);

                if (user == null)
                {
                    return(Unauthorized("Invalid email or password"));
                }

                var token = _jwtService.GenerateJwtToken(user);

                return(Ok(new { token }));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(StatusCode(500, e.Message));
            }
        }
예제 #3
0
        public async Task <ApiResponse <UserLoginResponseModel> > UserLogin(UserLoginRequestModel request)
        {
            try
            {
                var response = await this.httpClient.PostAsync(
                    "api/account/login",
                    new FormUrlEncodedContent(
                        new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("email", request.Email),
                    new KeyValuePair <string, string>("password", request.Password),
                }));

                var responseString = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return(new ApiResponse <UserLoginResponseModel>(new ApiError("Server error " + (int)response.StatusCode, responseString)));
                }

                var responseObject = JsonSerializer.Deserialize <UserLoginResponseModel>(responseString);
                return(new ApiResponse <UserLoginResponseModel>(responseObject));
            }
            catch (Exception ex)
            {
                return(new ApiResponse <UserLoginResponseModel>(new ApiError("HTTP Client", ex.Message)));
            }
        }
예제 #4
0
        public async Task <IActionResult> Login(UserLoginRequestModel userLoginRequestModel)
        {
            var user = await _userService.ValidateUser(userLoginRequestModel.Email, userLoginRequestModel.Password);

            if (user == null)
            {
                // Invalid User Name/Password
                return(View());
            }
            //if valid
            //cookie based authentication
            //claims, fName, lName, DOB
            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.Surname, user.LastName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.GivenName, user.FirstName)
            };
            // Identity
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            // create cookie

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity));

            return(RedirectToAction("Index", "Home"));
        }
예제 #5
0
        public UserLoginResponseModel Login([FromBody] UserLoginRequestModel userModel)
        {
            var responseMessage = this.TryExecuteOperation(() =>
            {
                var user = this.unitOfWork.userRepository.All()
                           .SingleOrDefault(
                    x => x.Username == userModel.Username &&
                    x.AuthCode == userModel.AuthCode);
                if (user == null)
                {
                    //throw new ArgumentException("User is not registered!");
                    return(new UserLoginResponseModel()
                    {
                        DisplayName = "",
                        AccessToken = ""
                    });
                }

                if (user.AccessToken == null)
                {
                    user.AccessToken = SessionGenerator.GenerateSessionKey(user.Id);
                    this.unitOfWork.userRepository.Update(user.Id, user);
                }

                return(UserLoginResponseModel.FromEntity(user));
            });

            return(responseMessage);
        }
예제 #6
0
        public ApiResponse UserLogin(UserLoginRequestModel request)
        {
            try
            {
                string stringSlq = "select * from AccountUser Where TenDangNhap = '" + request.UserName + "' and MatKhau = '" + request.Password + "' ";
                int    count     = db.TongBanGhi(stringSlq);

                if (count > 0)
                {
                    try
                    {
                        UserInformation = db.get_DaTaTable(stringSlq);
                        return(ApiResponse.Success(UserInformation)); // thành công
                    }
                    catch (Exception) {
                        return(ApiResponse.Error(-1)); // thất bại
                    }
                }
                else
                {
                    return(ApiResponse.Error(-1)); // thất bại
                }
            }
            catch (Exception)
            {
                return(ApiResponse.Error(-1));  // có lỗi

                throw;
            }
        }
예제 #7
0
        public ActionResult <ItemResponse <UserModel> > Login(UserLoginRequestModel req)
        {
            ActionResult result = null;

            try
            {
                UserModel currentUser = _userService.Login(req);

                if (currentUser.Id > 0)
                {
                    ItemResponse <UserModel> response = new ItemResponse <UserModel>();
                    response.Item = currentUser;
                    result        = Ok200(response);
                }
                else
                {
                    result = NotFound404(new ErrorResponse("User information did not match."));
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.ToString());
                result = StatusCode(500, new ErrorResponse(ex.Message.ToString()));
            }
            return(result);
        }
예제 #8
0
		public void Login()
		{
			HttpClientWrapper httpClientWrapper = new HttpClientWrapper(_baseUrl);
			UserLoginRequestModel userLoginRequestModel = new UserLoginRequestModel();

			var resp = httpClientWrapper.PostAsync<UserLoginRequestModel>("/api/v1/user/login", userLoginRequestModel);
		}
예제 #9
0
        public async Task <ResultModel <UserLoginResultModel> > Login(UserLoginRequestModel requestModel)
        {
            var discoveryDocumentRequest = new DiscoveryDocumentRequest
            {
                Address = ApplicationConfig.IdentityServer.Url,
                Policy  = new DiscoveryPolicy
                {
                    RequireHttps = false
                }
            };
            var client = new HttpClient();
            DiscoveryResponse discoveryResponse = await client.GetDiscoveryDocumentAsync(discoveryDocumentRequest);

            if (discoveryResponse.IsError)
            {
                return(ResultModel <UserLoginResultModel> .Fail("连接认证服务器失败"));
            }
            TokenResponse tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address      = discoveryResponse.TokenEndpoint,
                ClientId     = ClientType.Web.ToString(),
                ClientSecret = ApplicationConfig.IdentityServer.Secret,
                UserName     = requestModel.Account,
                Password     = requestModel.Password,
                Scope        = ApplicationConfig.IdentityServer.Scope
            });

            if (tokenResponse.IsError)
            {
                return(ResultModel <UserLoginResultModel> .Fail(tokenResponse.ErrorDescription));
            }
            var result = new UserLoginResultModel(tokenResponse.Raw.JsonToObject <TokenResultModel>());

            return(ResultModel <UserLoginResultModel> .Success(result, "登录成功"));
        }
예제 #10
0
        public async Task <IActionResult> Login(UserLoginRequestModel loginRequest, string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            if (!ModelState.IsValid)
            {
                return(View());
            }

            var user = await _userService.ValidateUser(loginRequest.Email, loginRequest.Password);

            //user not exist or wrong password
            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(View());
            }

            //if user is validated
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.Email),
                new Claim(ClaimTypes.GivenName, user.FirstName),
                new Claim(ClaimTypes.Surname, user.LastName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            //AuthenticationScheme will look in startup and check the default auth
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity));

            return(LocalRedirect(returnUrl));
        }
예제 #11
0
        public string GenerateJSONWebToken(UserLoginRequestModel userInfo)
        {
            UserModel user = userDataService.getFullUserByName(userInfo.Username).Result;

            if (user == null)
            {
                throw new NotFoundException("User does not exist");
            }
            bool isProvidedPasswordCorrect = userDataService.isUserPasswordCorrect(user.Password, userInfo.Password);

            if (!isProvidedPasswordCorrect)
            {
                throw new BadRequestException("Entered password does not match the existing one!");
            }

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username),
                new Claim(JwtRegisteredClaimNames.Email, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                                             _config["Jwt:Issuer"],
                                             claims,
                                             expires: DateTime.Now.AddMinutes(120),
                                             signingCredentials: credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
예제 #12
0
        public async Task <IActionResult> Login(UserLoginRequestModel userLoginRequestModel)
        {
            var user = await _userService.ValidateUser(userLoginRequestModel.Email, userLoginRequestModel.Password);

            if (user == null)
            {
                return(View());
            }
            //if user entered correct un/pw
            //Cookie based Auth
            //Claims firstlastname.dob.can be encrypted

            var claims = new List <Claim>()
            {
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.Surname, user.LastName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.GivenName, user.FirstName)
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            // create cookie

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity));

            return(RedirectToAction("Index", "Home"));
        }
        public async Task <IActionResult> Login([FromForm] UserLoginRequestModel input)
        {
            var user = await this.userManager.FindByEmailAsync(input.Email);

            if (user == null || user.IsDeleted)
            {
                return(this.BadRequest(new ErrorResponseModel
                {
                    Description = "No such user",
                }));
            }

            var validCredentials = await this.userManager.CheckPasswordAsync(user, input.Password);

            if (!validCredentials)
            {
                return(this.BadRequest(new ErrorResponseModel
                {
                    Description = "Email or password is incorrect",
                }));
            }

            // sample code to run if user's credentials is valid and before login
            // if (!await this.userManager.IsInRoleAsync(user, GlobalConstants.AdministratorRoleName))
            // {
            //    return this.BadRequest(new { Message = "You need higher permission to access this functionality" });
            // }

            // var result = await this.signInManager
            //   .PasswordSignInAsync(input.Email, input.Password, isPersistent: false, lockoutOnFailure: false);
            // FOR JWT not use PasswordSignInAsync but CheckPasswordSignInAsync - the second DO NOT SEND Cookie from
            // the Identiry server!
            var result = await this.signInManager
                         .CheckPasswordSignInAsync(user, input.Password, lockoutOnFailure : false);

            if (!result.Succeeded)
            {
                return(this.BadRequest(new ErrorResponseModel
                {
                    Description = "Invalid login attempt",
                }));
            }

            var response = await this.accountsService.Authenticate(user);

            //// the name of the cookie is given by the Framework, can be changed by the Identity Server post configuration
            // this.Response.Cookies.Append(GlobalConstants.JwtCookieName, response.AccessToken, new CookieOptions
            // {
            //    HttpOnly = true,
            //    Secure = true,
            //    // MaxAge = TimeSpan.FromTicks(response.ExpiresIn),
            //    // MaxAge = TimeSpan.FromTicks(60),
            //    // Expires = DateTimeOffset.UtcNow.AddMinutes(1),
            //    // SameSite = SameSiteMode.None,
            // });

            // return this.Ok(this.User.Identity.IsAuthenticated);
            return(this.Ok(response));
        }
예제 #14
0
        public IResponse <UserLoginResponseModel> Login(UserLoginRequestModel model)
        {
            try
            {
                var loginUser = UserRepository.GetUser(model.UserName, Encryption.CreateMD5(model.Password));

                if (loginUser == null)
                {
                    return(Fail <UserLoginResponseModel>("User Not Found"));
                }
                else
                {
                    var UserRoles       = UserRepository.GetUserRoles(loginUser.ID);
                    var returnRolesName = new List <string>();
                    foreach (var role in UserRoles)
                    {
                        returnRolesName.Add(role.RoleName);
                    }
                    //token generation

                    //security key
                    string securityKey = _configuration.GetSection("AppSettings").GetSection("JWTKey").Value;
                    //symetric security key
                    var symetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
                    //signIn Credentials
                    var signInCredentials = new SigningCredentials(symetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
                    var claims            = new List <Claim>();

                    claims.Add(new Claim(ClaimTypes.NameIdentifier, loginUser.UserName));
                    foreach (var role in UserRoles)
                    {
                        claims.Add(new Claim(ClaimTypes.Role, role.Description));
                    }

                    //token
                    var token = new JwtSecurityToken(
                        issuer: "api1",
                        audience: "api1",
                        expires: DateTime.Now.AddHours(1),
                        signingCredentials: signInCredentials,
                        claims: claims
                        );


                    return(Ok <UserLoginResponseModel>(new UserLoginResponseModel()
                    {
                        ID = loginUser.ID,
                        UserName = loginUser.UserName,
                        UserFullName = loginUser.FirstName + " " + loginUser.LastName,
                        Token = new JwtSecurityTokenHandler().WriteToken(token)
                    }));
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #15
0
        public async Task <IActionResult> Login([FromBody] UserLoginRequestModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userService.Login(model.Email, model.Password);

                return(Ok(user));
            }
            return(BadRequest("Please check the data you entered"));
        }
예제 #16
0
        public async Task <ActionResult> Login(UserLoginRequestModel loginRequest)
        {
            //Http is stateless means each and every request is indepent of each other
            // 10:00 AM u1 -> http: localhost / movies / index
            // 10:00 AM u2 -> http:localhost/movies/index
            // 10:00 AM u3 -> http:localhost/movies/index
            // 10:01 AM u1 -> http:localhost/account/login, we can create an autheticate cookie
            //cookie is one way of storing information on browser,
            //localstorage and sessionstorage, cookies,
            //if there are any cookies present then those cookies will be automatically sent to the server.

            // 10:02 AM u1 -> http:localhost/user/purchases --->we are expecting a page that shows movies bought by user1
            //we need to check if the cookie is expired or not and valid or not
            //Cookies is one way of state mangement, client-side
            // 10:01 AM u2 -> http:localhost/account/login

            if (ModelState.IsValid)
            {
                //call service layer to validate user
                var user = await _userService.ValidatUser(loginRequest.Email, loginRequest.Password);  //duandian

                if (user == null)
                {
                    ModelState.AddModelError(string.Empty, "Invalid Login");
                }

                //We want to show First Name, Last Name on header (Navigation bar)

                //Step1:Use Claims, create a claims based on your application needs

                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.GivenName, user.FirstName),
                    new Claim(ClaimTypes.Surname, user.LastName),
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.Email),
                };

                //Step2: we need to create an indentity object to hold those claims
                var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                //Step3: Finally, we are going to create a cookie that will be attached to the HTTP response
                //HttpContext is probably the most improtant class in ASP.NET that holds all the information regarding that Http Request/Response
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity));

                //manually creating cookie
                //HttpContext.Response.Cookies.Append("NewCookieName", "English"); //para1: Cookie Name, para2: Content

                //Once ASP.Net Creates Authentication Cookies, it will check for that cookie in the HttpRequest and see if the cookie is not expired
                //and it will decrypt the information present in the Cookie and check whether User is Authenticated and will also get claims from the cookies
                return(LocalRedirect("~/")); //return to one level up which is the home page
            }

            return(View());
        }
        public HttpResponseMessage login(UserLoginRequestModel userLoginRequestModel)
        {
            AuthProvider authProvider = new AuthProvider();
            ErrorModel   errorModel   = new ErrorModel();

            APIResponseModel responseModel = new APIResponseModel();

            responseModel.Response = authProvider.login(userLoginRequestModel, out errorModel);
            responseModel.Error    = errorModel;
            return(Request.CreateResponse(HttpStatusCode.OK, responseModel));
        }
        public IActionResult Authenticate([FromBody] UserLoginRequestModel userParam)
        {
            var user = _userService.Authenticate(userParam);

            if (user == null)
            {
                return(BadRequest(new { message = "Kullanici veya şifre hatalı!" }));
            }

            return(Ok(user));
        }
        public async Task <ActionResult> LoginAsync(UserLoginRequestModel loginRequest)
        {
            var user = await _userService.ValidateUser(loginRequest.Email, loginRequest.Password);

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

            return(Ok());
        }
예제 #20
0
        public async Task <IActionResult> Login([FromBody] UserLoginRequestModel model)
        {
            UserLoginResponseModel response = await this._authorizationService.Login(model);

            if (!response.Succeeded)
            {
                this.ModelState.AddModelError("", "Invalid username or password");
                return(this.BadRequest(this.ModelState));
            }

            return(this.Ok(response));
        }
예제 #21
0
        public UserModel Login(UserLoginRequestModel req)
        {
            UserModel currentUser = new UserModel();

            {
                UserLoginModel userInfo      = Get(req.Email);
                bool           validPassword = BCrypt.Net.BCrypt.Verify(req.Password, userInfo.Password);

                if (validPassword)
                {
                    currentUser = userInfo;
                }
            }
            return(currentUser);
        }
예제 #22
0
        public async Task <IActionResult> LoginASync(UserLoginRequestModel userLoginRequestModel)
        {
            var user = await _userService.ValidateUser(userLoginRequestModel.Email, userLoginRequestModel.Password);

            if (user == null)
            {
                return(Unauthorized());
            }
            var JwtToken = GenreateJWT(user);

            // if user entered valid user/pw
            // create JWT Token

            return(Ok(new { token = JwtToken }));
        }
예제 #23
0
        public async Task <IActionResult> Post([FromBody] UserLoginRequestModel request)
        {
            var authResponse = await _identityService.LoginAsync(request.Email, request.Password);

            if (!authResponse.Success)
            {
                return(Unauthorized(new ErrorResponseModel(authResponse.Errors)));
            }

            return(Ok(new AuthSuccessResponseModel
            {
                authToken = authResponse.AuthToken,
                refreshToken = authResponse.RefreshToken
            }));
        }
예제 #24
0
        /// <summary>
        ///     Login
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <bool> Login(UserLoginRequestModel request)
        {
            IReliableDictionary <string, UserState> myDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, UserState> >("Users");

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                ConditionalValue <UserState> result = await myDictionary.TryGetValueAsync(tx, request.CellPhone);

                if (result.HasValue)
                {
                    return(result.Value.PassWord.Equals(request.PassWord, StringComparison.OrdinalIgnoreCase));
                }
            }
            return(false);
        }
예제 #25
0
        public UserLoginResponseModel login(UserLoginRequestModel userLoginRequestModel, out ErrorModel errorModel)
        {
            errorModel = null;
            try
            {
                Auth authHelper = new Auth();
                UserLoginResponseModel loginResponseModel = authHelper.login(userLoginRequestModel, out errorModel);

                return(loginResponseModel);
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #26
0
        public async Task <IActionResult> LoginUser(UserLoginRequestModel req)
        {
            if (ModelState.IsValid)
            {
                var loginResult = await _userService.ValidateUser(req.Email, req.Password);

                if (loginResult == null)
                {
                    return(Unauthorized(new { message = "Please check your credentials" }));
                }
                //success, generate JWT here
                var token = GenerateJWT(loginResult);
                return(Ok(new { token }));
            }
            return(BadRequest(new { message = "Please check the info you entered" }));
        }
예제 #27
0
        public async Task <IActionResult> Login(UserLoginRequestModel model)
        {
            // check un/pw is correct
            var user = await _userService.Login(model.Email, model.Password);

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

            var jwt = CreateJWT(user);

            // user entered correct password
            // we create a token JWT which includes the user information and send it to Angular application

            return(Ok(new { token = jwt }));
        }
예제 #28
0
        public async Task <IActionResult> Login(UserLoginRequestModel model)
        {
            var user = await _userService.Login(model.Email, model.Password);

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

            // user entered his correct un/pw
            // we will create a cookie, movieshopauthcookie =>FirstName, LastName, id, Email, expiration time , claims
            // Cookie based Authentication.
            // 2 hours
            //

            // create claims object and store required information
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.GivenName, user.FirstName),
                new Claim(ClaimTypes.Surname, user.LastName),
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email),
            };

            if (user.Roles != null)
            {
                claims.AddRange(user.Roles.Select(role => new Claim(ClaimTypes.Role, role)));
            }

            // HttpContext =>
            // method type => get/post
            // Url
            // browsers
            // headers
            // form
            // cookies

            // create an identity object
            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            // create a cookie that stores the identity information
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity));

            return(LocalRedirect("~/"));
        }
예제 #29
0
        public async Task <IActionResult> PutUserLogin(
            [FromRoute] string userId,
            [FromRoute] string providerType,
            [FromRoute] string providerId,
            [FromBody] UserLoginRequestModel userLoginModel)
        {
            // Currently only support "password" provider
            providerType = providerType.ToLowerInvariant();
            if (providerType != LoginProvider.UserNamePassword)
            {
                _logger.LogInformation("PutUserLogin: Unsupported ProviderType '{0}'", providerType);
                return(this.ValidationFailed(new ErrorDetail("providerType", "Unsupported provider type")));
            }

            // TODO Add password complexity options!
            var user = await _userStore.GetUserByIdAsync(userId);

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

            user.Logins = user.Logins ?? new List <Login>();
            var login = user.Logins?.FirstOrDefault(l => l.ProviderType == providerType && l.ProviderId == providerId);

            if (login == null)
            {
                login = new Login
                {
                    ProviderType = providerType,
                    ProviderId   = providerId,
                };
                user.Logins.Add(login);
            }
            // Set Password
            login.ProviderData = _passwordHasher.HashPassword(userLoginModel.Password);

            await _userStore.SaveUserAsync(user);

            return(CreatedAtRoute(nameof(DeleteUserLogin), new { userId, providerType, providerId }, null));
        }
예제 #30
0
        public IActionResult Login([FromBody] UserLoginRequestModel login)
        {
            try
            {
                if (login.Username.Length < 4 || login.Username.Length > 40)
                {
                    throw new BadRequestException("Incorrect Data! Username must between " + 4 + " and " + 40 + " symbols!");
                }
                if (login.Password.Length < 6 || login.Password.Length > 40)
                {
                    throw new BadRequestException("Incorrect Data! Password must between " + 6 + " and " + 40 + " symbols!");
                }
                string jwt = _jWTService.GenerateJSONWebToken(login);

                CookieOptions cookieOptions = new CookieOptions();
                cookieOptions.Expires = DateTime.Now.AddMinutes(120);

                Response.Cookies.Append("Auth-Tst", jwt);

                IActionResult response = Ok();
                return(response);
            } catch (Exception e)
            {
                if (e.GetType().Name.Equals("BadRequestException"))
                {
                    Response.StatusCode = 400;
                    return(Content(e.Message));
                }
                else if (e.GetType().Name.Equals("NotFoundException"))
                {
                    Response.StatusCode = 404;
                    return(Content(e.Message));
                }
                else
                {
                    Response.StatusCode = 500;
                    return(Content(e.Message));
                }
            }
        }