public HttpResponseMessage Login(ApiController controller, SSOUserRequest request)
        {
            try
            {
                // Check if signature is valid
                var isSignatureValid = _signatureService.IsValidClientRequest(request.ssoUserId, request.email, request.timestamp, request.signature);
                if (!isSignatureValid)
                {
                    var httpResponse = new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent("Invalid Session")
                    };
                    return(httpResponse);
                }
                // Check if user exists
                if (_userService.IsUsernameFound(request.email))
                {
                    var generatedToken = _jwtService.CreateToken(request.email, _userService.GetUserUid(request.email));
                    var redirectURL    = baseRedirectURL + generatedToken;
                    var redirect       = controller.Request.CreateResponse(HttpStatusCode.SeeOther);
                    redirect.Content          = new StringContent(redirectURL);
                    redirect.Headers.Location = new Uri(redirectURL);

                    return(redirect);
                }
                else
                {
                    // If user doesn't have account in greetngroup, create account
                    User createdUser = new User
                    {
                        UserId   = _userService.GetNextUserID(),
                        UserName = request.email
                    };
                    _userService.InsertUser(createdUser);
                    _userClaimService.AddDefaultClaims(createdUser);
                    var generatedToken = _jwtService.CreateToken(request.email, _userService.GetUserUid(request.email));
                    var redirectURL    = baseRedirectURL + generatedToken;
                    var redirect       = controller.Request.CreateResponse(HttpStatusCode.SeeOther);
                    redirect.Content          = new StringContent(redirectURL);
                    redirect.Headers.Location = new Uri(redirectURL);

                    return(redirect);
                }
            }
            catch (Exception e)
            {
                var httpResponse = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("Unable to login at this time")
                };
                return(httpResponse);
            }
        }
        public async Task <IActionResult> SignIn([FromBody] CredentialModel model)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(model.UserName))
                {
                    throw new InvalidOperationException("UserName is required!");
                }

                var manToMachine = model.GameMode == "auto" || string.IsNullOrWhiteSpace(model.GameMode);

                var token = await _jwtService.CreateToken(model.UserName);

                await _gameSerivce.SignIn(model.UserName, manToMachine);

                if (manToMachine)
                {
                    await _gameSerivce.SignIn("Machine", true);
                }

                return(Ok(new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token),
                    expiration = token.ValidTo
                }));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Exception thrown while creating JWT: {ex}");
            }

            return(BadRequest("Failed to generate token"));
        }
        public async Task <AuthSuccessResult> Refresh(refreshViewModel model)
        {
            var token = await _refreshTokens.GetQueryable(x => x.Token == model.refresh).Include(x => x.User).FirstOrDefaultAsync();

            var refresh_time = _configuration.GetSection("JWT").GetValue <int>("REFRESH_LIFETIME");

            if (token == null)
            {
                throw new Exception("We can't find your token...");
            }

            if (token.ToLife.AddMinutes(refresh_time) <= DateTime.Now)
            {
                throw new Exception("Refresh token is expired...");
            }

            var handler       = new JwtSecurityTokenHandler();
            var decrypt_token = handler.ReadJwtToken(model.token);

            if (decrypt_token.Claims.FirstOrDefault(x => x.Type == ClaimsIdentity.DefaultNameClaimType).Value != token.User.Id)
            {
                throw new Exception("Unknown error...");
            }

            return(new AuthSuccessResult()
            {
                access_token = _jWTService.CreateToken(token.User),
                refresh_token = _jWTService.CreateRefreshToken(token.User),
                ava = token.User.img
            });
        }
Exemple #4
0
        public bool IsAuthenticated(LoginRequestDTO request, out TnToken token)
        {
            token = null;
            if (!_userService.IsValid(request))
            {
                return(false);
            }
            TnToken data = _jWTService.CreateToken <LoginRequestDTO>(request);

            token = data;
            return(true);
        }
Exemple #5
0
        public async Task <ActionResult <AppUserViewModel> > Login(LoginRequestViewModel loginRequestViewModel)
        {
            var appUser = await _userManager.FindByEmailAsync(loginRequestViewModel.Email);

            if (appUser == null)
            {
                return(Unauthorized(new APIResponse(StatusCodes.Status401Unauthorized)));
            }

            var signInResult = await _signInManager.CheckPasswordSignInAsync(appUser, loginRequestViewModel.Password, false);

            if (!signInResult.Succeeded)
            {
                return(Unauthorized(new APIResponse(StatusCodes.Status401Unauthorized)));
            }

            return(new AppUserViewModel
            {
                FullName = appUser.FullName,
                Email = appUser.Email,
                Token = _jwtService.CreateToken(appUser)
            });
        }
        public async Task <ResultDTO> Login([FromBody] UserLoginDTO model)
        {
            if (!ModelState.IsValid)
            {
                return(new ResultErrorDTO
                {
                    Status = 400,
                    Message = "ERROR",
                    Errors = CustomValidator.GetErrorsByModel(ModelState)
                });
            }
            else
            {
                var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);

                if (!result.Succeeded)
                {
                    _logger.LogInformation($"User: email: {model.Email} login failed");
                    List <string> error = new List <string>();
                    error.Add("User is not found, password or email isn't correct!");
                    return(new ResultErrorDTO
                    {
                        Status = 400,
                        Message = "user not found!",
                        Errors = error
                    });
                }
                else
                {
                    var user = await _userManager.FindByEmailAsync(model.Email);

                    await _signInManager.SignInAsync(user, false);

                    _logger.LogInformation($"User: email: {model.Email} login success");
                    return(new ResultLoginDTO
                    {
                        Status = 200,
                        Message = "OK",
                        Token = _jwtTokenService.CreateToken(user)
                    });
                }
            }
        }
Exemple #7
0
        public LoginResponse Authenticate(string username, string password)
        {
            var user = _context.Users.Where(x => x.Username == username).FirstOrDefault();

            if (user == null)
            {
                throw new Exception("No user with that username");
            }

            if (!_hashingService.Verify(password, user.PasswordHash))
            {
                throw new Exception("Invalid credentials");
            }

            var token    = _userJwtService.CreateToken(user.Id);
            var response = new LoginResponse();

            response.Username   = username;
            response.Token      = token.Token;
            response.ExpiryDate = token.ExpiryDate;
            return(response);
        }
        public async Task <object> GetToken([FromBody] LoginViewModel model)
        {
            var result = await _jwtService.CreateToken(model.UserName, model.Password);

            return(result);
        }
Exemple #9
0
        private string GenerateToken(long userId)
        {
            var token = _jwtService.CreateToken(userId);

            return(token);
        }