public IActionResult Login([FromBody] User user)
        {
            var _user = _db.Users.FirstOrDefault(u => u.Email == user.Email);

            if (_user != null && HashPassHelper.Check(_user.Password, user.Password))
            {
                //Generar JWT
                var tokenString = GenerateJWT.Gen(_user);

                //Almacenar y enviar en una cookie
                HttpContext.Response.Headers.Add(
                    "Authorization",
                    "Bearer " + tokenString
                    );

                HttpContext.Response.Cookies.Append(

                    "SSID", // No tocar hasta solucionar verificacion
                    Guid.NewGuid().ToString(),
                    new CookieOptions
                {
                    Expires  = DateTime.Now.AddDays(1),
                    HttpOnly = false,     // No tocar hasta solucionar verificacion
                    Secure   = false
                });

                return(Ok());
            }

            else
            {
                return(Unauthorized());
            }
        }
示例#2
0
        public IActionResult LoginUser([FromBody] UserModel login)
        {
            IActionResult response = Unauthorized();
            var           msg      = new MessageModel <UserModel>();
            var           res      = DbClientFactory <UserDbClient> .Instance.AuthenticateUser(login, ConnectionString.Value.cs);

            if (res == "C200")
            {
                msg.IsSuccess     = true;
                msg.ReturnMessage = "User Login successfully";

                UserModel user = null;

                user = new UserModel {
                    Email = login.Email, Password = login.Password
                };

                GenerateJWT c = new GenerateJWT(ConnectionString);


                var tokenString = c.GenerateJSONWebToken(user);
                response = Ok(new { token = tokenString });
            }
            else
            {
                msg.IsSuccess     = false;
                msg.ReturnMessage = "Invalid Email or Password";
            }
            return(response);
        }
示例#3
0
        public IActionResult Login([FromBody] LoginVM user)
        {
            //TO DO: MAKE THE MUTLPIPLE ACCOUNTS SHOW UP WHEN THE USER THEM

            if (!ModelState.IsValid)
            {
                return(Json(new JSONResponseVM {
                    success = false, message = "Model state is incorrect"
                }));
            }

            string password = HashString.HashThat(user.password, config["salt"]);

            User theUser = context.Users.Where(u => u.username == user.username && u.password == password).FirstOrDefault();

            if (theUser != null)
            {
                return(Json(new JSONResponseVM {
                    success = true, message = GenerateJWT.Generate(
                        theUser.userId.ToString(),
                        theUser.portfolioId1.ToString(),
                        config)
                }));
            }
            else
            {
                return(Json(new JSONResponseVM {
                    success = false, message = "Incorrect login details"
                }));
            }
        }
示例#4
0
        public async Task <JsonResult> Login([FromBody] LoginVM loginUser)
        {
            //hash the password
            string password = HashString.Hash(loginUser.password, config["salt"]);

            var user = await context.Users
                       .Where(u => u.username == loginUser.username)
                       .Where(u => u.hashedPassword == password)
                       .FirstOrDefaultAsync();

            if (user != null)
            {
                //Generate the JWT
                GenerateJWT jwtGen = new GenerateJWT();
                TokenVM     token  = jwtGen.Generate(user.username, config);
                return(Json(new JSONTokenResponseVM {
                    message = "Successfully logged in", token = token.token
                }));
            }
            else
            {
                return(Json(new JSONResponseVM {
                    success = false, message = "Incorrect login details"
                }));
            }
        }
        public ActionResult <RefreshRequest> Refresh([FromBody] RefreshRequest refreshRequest)
        {
            DealingWithRefreshToken dealingWithRefreshToken = new DealingWithRefreshToken();

            string refreshToken = Request.Headers["Authorization"].ToString().Split(" ")[1];

            refreshRequest.RefreshToken = refreshToken;
            int userId = dealingWithRefreshToken.GetUserIdFromAccessToken(refreshRequest.AccessToken, _jwtSettings.SecretKey);

            Users userFromDbViaAccessToken = _context.Users.FirstOrDefault(u => u.Id == userId);

            TblRefreshToken refreshTokenUser = _context.TblRefreshToken
                                               .Where(rt => rt.RefreshToken == refreshToken)
                                               .OrderByDescending(x => x.ExpiryDate)
                                               .FirstOrDefault();

            if (userFromDbViaAccessToken != null && dealingWithRefreshToken.ValidateRefreshToken(refreshTokenUser, userFromDbViaAccessToken, refreshToken))
            {
                UserDTO userWithTokens = _mapper.Map <UserDTO>(userFromDbViaAccessToken);
                userWithTokens.Token = GenerateJWT.CreateJWT(userFromDbViaAccessToken.Id, _jwtSettings.SecretKey, DateTime.UtcNow.AddSeconds(_expiryTimeSeconds));
                RefreshRequest userTokens = new RefreshRequest();

                var userFromDb = _context.TblRefreshToken.FirstOrDefault(x => x.User.RegistrationToken == refreshRequest.AccessToken);
                userFromDb.User.RegistrationToken = userWithTokens.Token;
                string newRefreshToken = Guid.NewGuid().ToString();
                userFromDb.RefreshToken = newRefreshToken;

                _context.SaveChanges();
                userTokens.AccessToken  = userWithTokens.Token;
                userTokens.RefreshToken = newRefreshToken;
                return(Ok(userTokens));
            }
            return(null);
        }
示例#6
0
        public async Task <ActionResult <UserDTO> > Login([FromBody] LoginDTO userClaims)
        {
            DealingWithRefreshToken dealingWithRefreshToken = new DealingWithRefreshToken();
            Users user = _loginRepository.GetUserOrDefault(userClaims);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect..." }));
            }

            UserDTO userDTO = _mapper.Map <UserDTO>(user);

            TblRefreshToken refreshToken = dealingWithRefreshToken.GenerateRefreshToken(_expiryTimeSeconds);

            user.TblRefreshToken.Add(refreshToken);

            var    tokenHandler = new JwtSecurityTokenHandler();
            string accessToken  = GenerateJWT.CreateJWT(userDTO.Id, _jwtSettings.SecretKey, DateTime.UtcNow.AddSeconds(_expiryTimeSeconds));

            userDTO.RefreshToken   = refreshToken.RefreshToken;
            userDTO.Token          = accessToken;
            user.RegistrationToken = accessToken;

            await _context.SaveChangesAsync();

            return(userDTO);
        }
示例#7
0
        public async Task <IActionResult> SignInAsync(string document, string password)
        {
            HttpStatusCode     statusCode = HttpStatusCode.OK;
            ResponseSignInUser response   = new ResponseSignInUser();

            try
            {
                var result = await _users.LoginAsync(document, password);

                if (result.Succeeded)
                {
                    //Get JWT TOKEN
                    GenerateJWT token          = new GenerateJWT(_configuration);
                    User        usuario        = _users.GetUserByIdentification(document);
                    var         userRegistered = await _userManager.FindByEmailAsync(usuario.Email);

                    response.IdUser = userRegistered.Id.ToString();
                    response.JWT    = token.GenerateTokenUser(userRegistered);
                    return(StatusCode((int)statusCode, response));
                }
                else if (result.IsNotAllowed)
                {
                    response.ErrorMessage = $"Failed to signIn user with identificacion: {document}, signIn is not allowed";
                    response.Errors.Add(response.ErrorMessage);
                }
                else
                {
                    response.ErrorMessage = "Credenciales inválidas";
                    response.Errors.Add(response.ErrorMessage);
                }

                statusCode            = HttpStatusCode.BadRequest;
                response.StatusCode   = (int)statusCode;
                response.IsSucessfull = false;
            }

            catch (DatabaseException e)
            {
                statusCode            = HttpStatusCode.InternalServerError;
                response.StatusCode   = (int)statusCode;
                response.IsSucessfull = false;
                response.ErrorMessage = e.Message;
                _logger.LogError(e, $"Failed to signIn user with identification: {document}");
            }

            catch (Exception e)
            {
                statusCode            = HttpStatusCode.InternalServerError;
                response.StatusCode   = (int)statusCode;
                response.IsSucessfull = false;
                response.ErrorMessage = "Internal server error";
                _logger.LogError(e, $"Failed to signIn user with identification: {document}");
            }

            return(StatusCode((int)statusCode, response));
        }
示例#8
0
        public async Task <JsonResult> CreateAccount([FromBody] CreateAccountVM account)
        {
            //validate

            if (account.username == null || account.password == null || account.password2 == null)
            {
                return(Json(new JSONResponseVM {
                    success = false, message = "Please fill out all the fields"
                }));
            }
            if (account.password != account.password2)
            {
                return(Json(new JSONResponseVM {
                    success = false, message = "Passwords don't match"
                }));
            }

            //check to see if this username already exists
            var query = await context.Users.Where(u => u.username == account.username).FirstOrDefaultAsync();

            if (query != null)
            {
                //this username exists
                return(Json(new JSONResponseVM {
                    success = false, message = "A user with this username already exists"
                }));
            }


            string newPassword = account.password;

            newPassword = HashString.Hash(newPassword, config["salt"]);

            //now add the new user to the database
            User newUser = new User
            {
                username       = account.username,
                hashedPassword = newPassword,
                //the user is by default a customer
                role_id = 0,
                role    = await context.Roles.Where(r => r.role_id == 0).FirstOrDefaultAsync()
            };

            context.Users.Add(newUser);
            context.SaveChanges();

            //generate the token
            GenerateJWT jwtGen = new GenerateJWT();
            TokenVM     tok    = jwtGen.Generate(newUser.username, config);

            return(Json(new JSONTokenResponseVM {
                message = "Successfully created account: " + newUser.username, token = tok.token
            }));
        }
        public async Task <IActionResult> SignInAsync(RequestIdentityRegister User)
        {
            HttpStatusCode     statusCode = HttpStatusCode.OK;
            ResponseSignInUser response   = new ResponseSignInUser();

            try
            {
                var result = await _signInManager.PasswordSignInAsync(User.Email, User.Password, true, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    //Get JWT TOKEN
                    GenerateJWT token          = new GenerateJWT(_configuration);
                    var         userRegistered = await _userManager.FindByEmailAsync(User.Email);

                    response.IdUser = userRegistered.Id.ToString();
                    response.JWT    = token.GenerateTokenUser(userRegistered);
                    return(StatusCode((int)statusCode, response));
                }
                else if (result.IsLockedOut)
                {
                    response.ErrorMessage = $"LockedOut account with email {User.Email}";
                }
                else if (result.IsNotAllowed)
                {
                    response.ErrorMessage = $"Failed to signIn user with email {User.Email}, signIn is not allowed";
                }
                else
                {
                    response.ErrorMessage = $"Failed to signIn user with email {User.Email}, invalid credentials";
                }

                statusCode            = HttpStatusCode.BadRequest;
                response.StatusCode   = (int)statusCode;
                response.IsSucessfull = false;
            }
            catch (Exception e)
            {
                statusCode            = HttpStatusCode.InternalServerError;
                response.StatusCode   = (int)statusCode;
                response.IsSucessfull = false;
                response.ErrorMessage = "Internal server error";
                _logger.LogError(e, $"Failed to signIn user with email {User.Email}");
            }

            return(StatusCode((int)statusCode, response));
        }