Exemple #1
0
        /// <summary>
        /// Method that signs in the user propagated from the Login endpoint
        /// </summary>
        public Response <LoggedInUserResponse> SignInUser(LoginRequest request)
        {
            var response        = new Response <LoggedInUserResponse>();
            var encodedPassword = EncodePassword(request.Password);
            var user            = _repository.Find(x => x.UserName.Equals(request.UserName) && x.Password.Equals(encodedPassword)).FirstOrDefault();

            if (user != null)
            {
                var tokenString = GenerateJSONWebToken(user);
                _logger.LogInfo("user singed in");
                response.Status = System.Net.HttpStatusCode.OK;
                var loggedInUser = new LoggedInUserResponse()
                {
                    JWT = tokenString
                };
                response.Payload = loggedInUser;
                return(response);
            }
            else
            {
                _logger.LogError("user sign in failed");
                response.Messages.Add(new ResponseMessage
                {
                    Type    = Contracts.Enums.ResponseMessageEnum.Exception,
                    Message = "The user does not exist",
                });
                response.Status = System.Net.HttpStatusCode.InternalServerError;
                return(response);
            }
        }
        public async Task <ActionResult <UserResponse> > Login([FromBody] LoginViewModel loginUser)
        {
            var username = loginUser.Username;
            var password = loginUser.Password;

            if (username == null || password == null)
            {
                return(Unauthorized("Missing username/password"));
            }

            var user = await _context.User
                       .Where(u => u.Username == username && u.Password == password)
                       .FirstOrDefaultAsync();

            if (user == null)
            {
                return(Unauthorized("Either username or password is wrong"));
            }

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim("FullName", $"{user.FirstName} {user.LastName}"),
                new Claim(ClaimTypes.Role, user.Role.ToString())
            };

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

            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(10),
                IssuedUtc    = DateTimeOffset.UtcNow,
                IsPersistent = true
            };

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

            var userResponse = new LoggedInUserResponse
            {
                Id        = user.Id,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                DOB       = user.DOB,
                Role      = user.Role.ToString()
            };

            return(Ok(userResponse));
        }
Exemple #3
0
        /// <summary>
        /// 获得当前登录用户
        /// </summary>
        /// <returns></returns>
        public string GetLoggedInUser()
        {
            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return("");
            }

            //如果是桌面程序则需要验证用户身份
            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (Uid < 1)
                {
                    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
                    return("");
                }
            }

            //if (Uid < 1)
            //{
            //    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
            //    return "";
            //}
            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return("");
            }


            if (Format == FormatType.JSON)
            {
                return(string.Format("\"{0}\"", Uid));
            }

            LoggedInUserResponse loggeduser = new LoggedInUserResponse();

            //loggeduser.List = true;
            loggeduser.Uid = Uid;

            return(SerializationHelper.Serialize(loggeduser));
        }
Exemple #4
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP && commandParam.LocalUid < 1)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                return(false);
            }

            if (commandParam.Format == FormatType.JSON)
            {
                result = string.Format("\"{0}\"", commandParam.LocalUid);
            }
            else
            {
                LoggedInUserResponse loggeduser = new LoggedInUserResponse();
                loggeduser.Uid = commandParam.LocalUid;
                result         = SerializationHelper.Serialize(loggeduser);
            }
            return(true);
        }
Exemple #5
0
        public async Task <LoggedInUserResponse> Authenticate(string username, string password)
        {
            var userFromDb = await _userRepository.GetByNameAsync(username);

            // return null if user not found
            if (userFromDb == null)
            {
                throw new BadRequestException("Błędny login lub hasło.");
            }

            if (!VerifyPasswordHash(password, userFromDb.PasswordHash, userFromDb.PasswordSalt))
            {
                throw new BadRequestException("Błędny login lub hasło.");
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, userFromDb.Id.ToString()),
                    new Claim(ClaimTypes.Role, userFromDb.Role)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            LoggedInUserResponse loggedInUserResponse = new LoggedInUserResponse()
            {
                Id       = userFromDb.Id,
                Username = userFromDb.Username,
                Role     = userFromDb.Role,
                Token    = tokenString
            };

            return(loggedInUserResponse);
        }
Exemple #6
0
        /// <summary>
        /// 获得当前登录用户
        /// </summary>
        /// <returns></returns>
        public string GetLoggedInUser()
        {
            if (Signature != GetParam("sig").ToString())
            {
                ErrorCode = (int)ErrorType.API_EC_SIGNATURE;
                return "";
            }

            //如果是桌面程序则需要验证用户身份
            if (this.App.ApplicationType == (int)ApplicationType.DESKTOP)
            {
                if (Uid < 1)
                {
                    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
                    return "";
                }
            }

            //if (Uid < 1)
            //{
            //    ErrorCode = (int)ErrorType.API_EC_SESSIONKEY;
            //    return "";
            //}

            //float callid = Utils.StrToFloat(GetParam("call_id"), -1);
            //if (callid <= LastCallId)
            //{
            //    ErrorCode = (int)ErrorType.API_EC_CALLID;
            //    return "";
            //}

            if (CallId <= LastCallId)
            {
                ErrorCode = (int)ErrorType.API_EC_CALLID;
                return "";
            }


            if (Format == FormatType.JSON)
                return string.Format("\"{0}\"", Uid);

            LoggedInUserResponse loggeduser = new LoggedInUserResponse();
            //loggeduser.List = true;
            loggeduser.Uid = Uid;

            return SerializationHelper.Serialize(loggeduser);
        }
Exemple #7
0
        public override bool Run(CommandParameter commandParam, ref string result)
        {
            if (commandParam.AppInfo.ApplicationType == (int)ApplicationType.DESKTOP && commandParam.LocalUid < 1)
            {
                result = Util.CreateErrorMessage(ErrorType.API_EC_SESSIONKEY, commandParam.ParamList);
                return false;
            }

            if (commandParam.Format == FormatType.JSON)
                result = string.Format("\"{0}\"", commandParam.LocalUid);
            else
            {
                LoggedInUserResponse loggeduser = new LoggedInUserResponse();
                loggeduser.Uid = commandParam.LocalUid;
                result = SerializationHelper.Serialize(loggeduser);
            }
            return true;
        }