コード例 #1
0
        public async Task <IActionResult> RefreshToken([FromRoute] string refreshToken)
        {
            // TODO : better model validation
            if (string.IsNullOrEmpty(refreshToken))
            {
                return(BadRequest(new { error = "RefreshToken is empty or null." }));
            }

            BaseModel <UserModel> result = await _userService.RefreshAccessToken(refreshToken);

            if (result.HasError)
            {
                return(BadRequest(new { error = result.ErrorMessage }));
            }

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

            LoginResponseModel loginResponseModel = new LoginResponseModel();

            loginResponseModel.Token        = result.Data.Token;
            loginResponseModel.RefreshToken = result.Data.RefreshToken;

            loginResponseModel.User = new UserResponseModel()
            {
                Id        = result.Data.Id,
                Email     = result.Data.Email,
                CreatedAt = result.Data.CreatedAt,
                Type      = result.Data.Type
            };

            return(Ok(loginResponseModel));
        }
コード例 #2
0
        /// <summary>
        /// Valida o login
        /// </summary>
        /// <param name="loginRequest"></param>
        /// <returns></returns>
        public LoginResponseModel ValidateLogin(LoginRequestModel loginRequest)
        {
            string         msgErro    = null;
            MainRepository repository = new MainRepository();

            try
            {
                // Valida o parâmetro de entrada
                CheckLoginRequest(loginRequest);

                // Valida a conexão com o banco de dados
                repository.CheckDatabaseConnection(loginRequest);

                // Valida o Login
                CheckLogin(loginRequest, repository);
            }
            catch (Exception ex)
            {
                msgErro = ex.Message;
            }

            // Define o objeto login de resposta
            LoginResponseModel loginResponse = new LoginResponseModel();

            loginResponse.Login              = loginRequest?.Login;
            loginResponse.Password           = loginRequest?.Password;
            loginResponse.Company            = loginRequest?.Company;
            loginResponse.CredentialAccepted = String.IsNullOrEmpty(msgErro);
            loginResponse.ErrorMessage       = msgErro;

            return(loginResponse);
        }
コード例 #3
0
        public async Task <IActionResult> Login([FromBody] LoginRequestModel request)
        {
            // TODO : better model validation
            if (string.IsNullOrEmpty(request.Email) || string.IsNullOrEmpty(request.Password) || request.Password.Length < 6 || !RegexUtilities.IsValidEmail(request.Email))
            {
                return(BadRequest(new { error = "Email and Password fields are required and Password must be minimum length of '6'" }));
            }

            BaseModel <UserModel> result = await _userService.Login(request.Email, request.Password);

            if (result.HasError)
            {
                return(BadRequest(new { error = result.ErrorMessage }));
            }

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

            LoginResponseModel loginResponseModel = new LoginResponseModel();

            loginResponseModel.Token        = result.Data.Token;
            loginResponseModel.RefreshToken = result.Data.RefreshToken;

            loginResponseModel.User = new UserResponseModel()
            {
                Id        = result.Data.Id,
                Email     = result.Data.Email,
                CreatedAt = result.Data.CreatedAt,
                Type      = result.Data.Type
            };

            return(Ok(loginResponseModel));
        }
コード例 #4
0
        public LoginResponseModel Login(LoginRequestModel info)
        {
            NSLog.Logger.Info("Employee Login Start", info);
            LoginResponseModel user = null;

            try
            {
                using (CMS_Context _db = new CMS_Context())
                {
                    info.Password = CommonHelper.Encrypt(info.Password);
                    string serverImage = ConfigurationManager.AppSettings["PublicImages"];

                    var emp = _db.CMS_Employee.Where(o => o.Employee_Email == info.Email.ToLower().Trim() && o.Password == info.Password).FirstOrDefault();
                    if (emp != null)
                    {
                        user = new LoginResponseModel()
                        {
                            EmployeeID       = emp.Id,
                            EmployeeName     = emp.FirstName + " " + emp.LastName,
                            EmployeeEmail    = emp.Employee_Email,
                            EmployeeImageURL = string.IsNullOrEmpty(emp.ImageURL) ? "" : serverImage + "Employees/" + emp.ImageURL,
                            IsSupperAdmin    = emp.IsSupperAdmin,
                        };
                    }
                    NSLog.Logger.Info("Employee Login Done", user);
                }
            }
            catch (Exception ex) { NSLog.Logger.Error("Employee Login Error", ex); }
            return(user);
        }
コード例 #5
0
        public IActionResult Authenticate(LoginModel login)
        {
            if (ModelState.IsValid)
            {
                bool isValidUser   = false;
                var  loginResponse = new LoginResponseModel();

                var user = _context.Users.FirstOrDefault(x => string.Equals(x.Username, login.Username, StringComparison.OrdinalIgnoreCase));

                if (user != null)
                {
                    isValidUser = string.Equals(user.Password, login.Password);
                }

                if (isValidUser)
                {
                    string access_token = HelperClass.GetAccessToken(user);
                    loginResponse.IsAuthorized = true;
                    loginResponse.AccessToken  = access_token;
                    return(Ok(loginResponse));
                }
                else
                {
                    loginResponse.IsAuthorized = false;
                    loginResponse.ErrorMessage = ErrorMessageConstants.InvalidUser;
                    return(Unauthorized(loginResponse));
                }
            }

            return(BadRequest());
        }
コード例 #6
0
        public async Task <ResponseMessage> GetAuthToken([FromBody] GetAuthTokenViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(new ErrorResponseMessage(StatusCodeEnum.BadRequest, "Model state is invalid"));
            }

            var user = await _userManager.FindByIdAsync(model.Id);

            // check if user exists
            if (user == null)
            {
                return(new ErrorResponseMessage(StatusCodeEnum.BadRequest, "User not found"));
            }

            // check refresh token
            if (string.IsNullOrEmpty(user.RefreshToken) || user.RefreshToken != model.RefreshToken)
            {
                return(new ErrorResponseMessage(StatusCodeEnum.BadRequest, "Refresh token is incorrect"));
            }

            if (user.RefreshTokenValidUntil == null || user.RefreshTokenValidUntil <= DateTime.UtcNow)
            {
                return(new ErrorResponseMessage(StatusCodeEnum.BadRequest, "Refresh token is expired"));
            }

            var result = new LoginResponseModel(model.Id, user.UserName, await GetAuthToken(user), await GetRefreshToken(user));

            // update user
            user.RefreshToken           = result.RefreshToken.Token;
            user.RefreshTokenValidUntil = result.RefreshToken.ValidUntil;
            await _userManager.UpdateAsync(user);

            return(new SuccessResponseMessage(StatusCodeEnum.Ok, "Refresh token is correct", result));
        }
コード例 #7
0
        public async Task <ResponseMessage> Login([FromBody] LoginViewModel credentials)
        {
            if (!ModelState.IsValid)
            {
                return(new ErrorResponseMessage(StatusCodeEnum.BadRequest, "Model state is invalid"));
            }

            var user = await _userManager.FindByEmailAsync(credentials.Email);

            //check if user exists
            if (user == null)
            {
                return(new ErrorResponseMessage(StatusCodeEnum.BadRequest, "User not found"));
            }

            var identity = await GetClaimsIdentity(user.UserName, credentials.Password);

            if (identity == null)
            {
                return(new ErrorResponseMessage(StatusCodeEnum.BadRequest, "Invalid username or password"));
            }

            var result = new LoginResponseModel(identity.Claims.Single(c => c.Type == "id").Value, user.UserName, await GetAuthToken(user), await GetRefreshToken(user));

            // update user
            user.RefreshToken           = result.RefreshToken.Token;
            user.RefreshTokenValidUntil = result.RefreshToken.ValidUntil;
            await _userManager.UpdateAsync(user);

            return(new SuccessResponseMessage(StatusCodeEnum.Ok, "", result));
        }
コード例 #8
0
        public LoginResponseModel ResendOTP(LoginRequestModel requestModel)
        {
            IAuthentication    _repository = new DataAccess.Authentication.Authentication();
            LoginResponseModel objResponse = new LoginResponseModel();
            int Result = _repository.CheckPhoneNoExists(requestModel.UserName);

            if (Result > 0)
            {
                objResponse = _repository.GetRegisterOTPCountForUser(requestModel.UserName);
                DateTime Currentdate = DateTime.Now;
                DateTime OTPsentdate = Convert.ToDateTime(objResponse.RegisterOTPSentDate);
                int      reslt       = 0;
                if (objResponse.RegisterOTPSentDate == DateTime.MinValue)
                {
                    string OTP = GenerateNewOTP();
                    objResponse.OTP     = OTP;
                    objResponse.Status  = 1;
                    objResponse.Message = "You have Another 2 chance to send OTP";
                    SMSService.SendSms(requestModel.UserName, (objResponse.OTP), objResponse.OTP);
                    _repository.UpdateRegisterOTPCountForUser(requestModel.UserName, true);
                }
                else
                {
                    reslt = DateTime.Compare(Currentdate.Date, OTPsentdate.Date);

                    if (reslt != 0)
                    {
                        string OTP = GenerateNewOTP();
                        objResponse.OTP    = OTP;
                        objResponse.Status = 1;
                        objResponse.RegisterOTPSentCount = 1;
                        objResponse.Message = "You have Another 2 chance to send OTP";
                        SMSService.SendSms(requestModel.UserName, (objResponse.OTP), objResponse.OTP);
                        _repository.UpdateRegisterOTPCountForUser(requestModel.UserName, true);
                    }
                    else if (reslt == 0 && objResponse.RegisterOTPSentCount < 3)
                    {
                        string OTP = GenerateNewOTP();
                        objResponse.OTP    = OTP;
                        objResponse.Status = 1;
                        objResponse.RegisterOTPSentCount = objResponse.RegisterOTPSentCount + 1;
                        int balance = 3 - Convert.ToInt32(objResponse.RegisterOTPSentCount);
                        objResponse.Message = "You have another " + balance + " chance to send OTP";
                        SMSService.SendSms(requestModel.UserName, (objResponse.OTP), objResponse.OTP);
                        _repository.UpdateRegisterOTPCountForUser(requestModel.UserName, false);
                    }
                    else if (reslt == 0 && objResponse.RegisterOTPSentCount >= 3)
                    {
                        objResponse.Status = 2;
                        objResponse.RegisterOTPSentCount = 3;
                        objResponse.Message = "You have Exceeded the limit of resending OTP";
                    }
                }
            }
            else
            {
                objResponse.Status = 0;
            }
            return(objResponse);
        }
コード例 #9
0
        public LoginResponseObject ValidateUser(LoginRequestObject viewmodel)
        {
            LoginResponseObject objentity    = new LoginResponseObject();
            AppResponseView     objApp       = new AppResponseView();
            LoginResponseModel  objLoginResp = new LoginResponseModel();
            IAuthentication     _repository  = new DataAccess.Authentication.Authentication();

            objLoginResp           = _repository.ValidateUser(viewmodel.UserRequest);
            objentity.ResultObject = objLoginResp;
            if (objentity.ResultObject.Status == 1)
            {
                if (objentity.ResultObject.IsOTPverified == false)
                {
                    objentity.ResultObject.Status  = 0;
                    objentity.ResultObject.Message = "OTP Not Verified";
                }
                else
                {
                    objentity.ResultObject.Status  = 1;
                    objentity.ResultObject.Message = "Success";
                    objentity.ResultObject.user    = _repository.GetUserDetails(objentity.ResultObject.UserId);
                }
                //string OTP = GenerateNewOTP();
                //objLoginResp.OTP = OTP;
                //objentity.ResultObject = objLoginResp;
                //SMSService.SendSms(viewmodel.UserRequest.UserName, ("Login OTP " + objentity.ResultObject.OTP));
            }
            else
            {
                objentity.ResultObject.Message = "Invalid Credentials";
            }
            return(objentity);
        }
コード例 #10
0
ファイル: UserService.cs プロジェクト: patrykzzz/HomanAPI
 public Result <LoginResponseModel> Login(LoginRequestModel model)
 {
     try
     {
         var user = _userManager.FindByEmailAsync(model.Email)
                    .Result;
         if (user != null)
         {
             var isPasswordCorrect = _userManager.CheckPasswordAsync(user, model.Password)
                                     .Result;
             if (isPasswordCorrect)
             {
                 var token = new JwtSecurityTokenHandler()
                             .WriteToken(_tokenFactory.Create(user));
                 var response = new LoginResponseModel
                 {
                     UserId    = user.Id,
                     Token     = token,
                     Email     = model.Email,
                     FirstName = user.FirstName,
                     LastName  = user.LastName
                 };
                 return(Result <LoginResponseModel> .Success(response));
             }
         }
         return(Result <LoginResponseModel> .Fail());
     }
     catch (Exception)
     {
         return(Result <LoginResponseModel> .Fail());
     }
 }
コード例 #11
0
        public ActionResult <LoginResponseModel> Login([FromBody] LoginRequestModel Data)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    //Service that takes care for authenticating user and creating tokens
                    LoginResponseModel loginResponseModel = Services.UserServices.Login(Data, _Db, _configuration);
                    switch (loginResponseModel.Code)
                    {
                    //Successful login
                    case 0: return(Ok(loginResponseModel));

                    //Failed login
                    case 1: return(StatusCode(401, loginResponseModel));

                    //Error connecting DB
                    case 2: return(StatusCode(500, new { Message = "(Error: 102)There is a error in the Server. Please contact the Admin." }));
                    }
                    return(Ok(loginResponseModel));
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception e)
            {
                ///No error unhandled should be given to the outside world
                ///This catch block receives all unhandled exceptions that might escape all the try catch blocks
                return(StatusCode(500, Helpers.ExceptionHandler.Handle(e)));
            }
        }
コード例 #12
0
        public HttpResponseMessage PostLoginUser(UserModel model)
        {
            return(this.PerformOperationAndHandleExceptions(() =>
            {
                var context = this.ContextFactory.Create();
                using (context)
                {
                    var usernameToLower = model.Username.ToLower();
                    var usersDbSet = context.Set <User>();
                    var entity = usersDbSet.SingleOrDefault(usr => usr.Username == usernameToLower && usr.AuthenticationCode == model.AuthCode);
                    if (entity == null)
                    {
                        var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid username or password");
                        throw new HttpResponseException(errResponse);
                    }

                    entity.SessionKey = this.GenerateSessionKey(entity.Id);

                    context.SaveChanges();
                    var responseModel = new LoginResponseModel()
                    {
                        Nickname = entity.Username,
                        SessionKey = entity.SessionKey
                    };

                    var response = this.Request.CreateResponse(HttpStatusCode.Accepted, responseModel);
                    return response;
                }
            }));
        }
コード例 #13
0
        public LoginResponseModel Login(string userName, string password)
        {
            LoginResponseModel responseModel = new LoginResponseModel();

            try
            {
                using (JWTSampleDbContext dbContext = new JWTSampleDbContext())
                {
                    //Check user exists in db
                    var appUser = dbContext.ApplicationUser.Where(a => a.Username == userName && a.Password == password).FirstOrDefault();
                    if (appUser != null)
                    {
                        //Generate token
                        responseModel.Token = TokenProvider.GenerateToken(appUser);

                        UserInfo userInfo = new UserInfo();
                        userInfo.UserId    = appUser.UserId;
                        userInfo.UserName  = appUser.Username;
                        userInfo.Email     = appUser.Password;
                        responseModel.User = userInfo;
                    }
                }
                return(responseModel);
            }
            catch (Exception ex)
            {
                throw new Exception("Invalid Login");
            }
        }
コード例 #14
0
        public async Task <LoginResponseModel> ValidateUser(LoginRequestModel loginRequestModel)
        {
            var dbUser = await _userRepository.GetUserByEmail(loginRequestModel.Email);

            if (dbUser == null)
            {
                return(null);
            }
            var hashedPassword = _cryptoService.HashPassword(loginRequestModel.Password, dbUser.Salt);

            if (hashedPassword == dbUser.HashedPassword)
            {
                // User has entered correct password
                var roleResponseModels = new List <RoleResponseModel>();
                foreach (var r in dbUser.Roles)
                {
                    var cur = new RoleResponseModel();
                    cur.Id   = r.Id;
                    cur.Name = r.Name;
                    roleResponseModels.Add(cur);
                }
                var loginResponse = new LoginResponseModel
                {
                    Id          = dbUser.Id,
                    Email       = dbUser.Email,
                    FirstName   = dbUser.FirstName,
                    LastName    = dbUser.LastName,
                    DateOfBirth = dbUser.DateOfBirth, // DateTime cannot be convert to DateTime? implicitly but DateTime? can be convert to DateTime
                    Roles       = roleResponseModels
                };
                return(loginResponse);
            }
            return(null);
        }
コード例 #15
0
        public async Task <(LoginResponseModel, bool)> Login(LoginRequestModel loginRequest)
        {
            // attempt to login and exit if fails
            var(account, success) = await _accountService.Login(loginRequest);

            if (!success)
            {
                return(null, false);
            }

            // Use a secret
            var secret = Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JWT_SECRET"));

            // Create token handlers and descriptor
            var tokenHandler    = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(account.Claims),
                Expires            = DateTime.UtcNow.AddMinutes(30),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secret),
                                                            SecurityAlgorithms.HmacSha256Signature)
            };

            // Generating the token
            var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
            var model = new LoginResponseModel
            {
                Token  = tokenHandler.WriteToken(token),
                Id     = account.Guid,
                Name   = account.Name,
                Claims = account.Claims
            };

            return(model, true);
        }
コード例 #16
0
        public async Task <LoginResponseModel> ValidateUser(string email, string password)
        {
            // get the user info my email by using GetUserByEmail

            var dbUser = await _userRepository.GetUserByEmail(email);

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

            var hashedPassword = CreateHashedPassword(password, dbUser.Salt);

            if (hashedPassword == dbUser.HashedPassword)
            {
                // passwords match so create response model object

                var loginResponseModel = new LoginResponseModel
                {
                    Id = dbUser.Id, Email = dbUser.Email, FirstName = dbUser.FirstName, LastName = dbUser.LastName
                };
                return(loginResponseModel);
            }

            return(null);
        }
コード例 #17
0
        public LoginResponseModel LoginDemo(LoginTestBindingModel model)
        {
            //Admin admin = new Admin() {Admin_username=model.Username,Admin_pwd=model.Password };
            Admin admin    = _adminLog.GetByUsername(model.Username);
            int   validate = _adminLog.ValidateUser(model);
            ////MockAuthenticationService demoService = new MockAuthenticationService();
            ////Admin user = demoService.GetUser(model.Username, model.Password);
            LoginResponseModel loginresponse = new LoginResponseModel();

            if (validate == 0)
            {
                loginresponse.accesstoken = null;
                loginresponse.Admin_id    = -1;
                loginresponse.success     = false;
                //return N("Username or Password is Incorrect");
                return(loginresponse);//Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid Username or Password", Configuration.Formatters.JsonFormatter);
            }
            else
            {
                AuthenticationModule authentication = new AuthenticationModule();
                string token = authentication.GenerateTokenForUser(admin.Admin_username, admin.Admin_id);
                //string token = authentication.GenerateTokenForUser(model.sername, admin.Admin_id);
                loginresponse.accesstoken = token;
                loginresponse.Admin_id    = admin.Admin_id;
                loginresponse.success     = true;
                return(loginresponse); //Request.CreateResponse(HttpStatusCode.OK, token, Configuration.Formatters.JsonFormatter);
            }
        }
コード例 #18
0
    public void OnPointerUp(PointerEventData eventData)
    {
        if (_usernameInput.text.Length == 0 || _passwordInput.text.Length == 0)
        {
            return;
        }

        Dictionary <string, string> loginDict = new Dictionary <string, string>
        {
            { "username", _usernameInput.text }, { "password", _passwordInput.text }
        };

        UnityWebRequest request = UnityWebRequest.Post("http://127.0.0.1:8000/login", loginDict);

        request.SendWebRequest();
        while (!request.isDone)
        {
            new WaitForSeconds(0.5f);
        }

        if (request.responseCode == 201)
        {
            string             responseBody = request.downloadHandler.text;
            LoginResponseModel level        = JsonUtility.FromJson <LoginResponseModel>(responseBody);

            DownloadData(level.version);
            MusicManager.LoadAllMusicClips();
            MusicManager.PlayMenuMusic();
            SceneManager.LoadScene("Scenes/MainMenuScene", LoadSceneMode.Single);
        }
    }
コード例 #19
0
        public virtual ActionResult EditProfile(LoginModel model)
        {
            var response        = new LoginResponseModel();
            var currentIdentity = GetCurrentIdentity();

            if (!currentIdentity.IsAuthenticated)
            {
                // not logged in
                return(JsonNetResult(response));
            }

            var id       = model != null ? model.Id : null;
            var settings = SettingsHelper.Get(id, true);

            if (!ModelState.IsValid)
            {
                if (settings.DebugMode)
                {
                    var errorList = ModelState.Values.SelectMany(m => m.Errors)
                                    .Select(e => e.ErrorMessage)
                                    .ToList();

                    Logger.Debug("Invalid login request. ModelState Errors:\n" + string.Join(". ", errorList));
                }
                return(JsonNetResult(response));
            }

            // attempt to update the user profile
            MembershipHelper.UpdateProfile(model, settings, ref response);
            return(JsonNetResult(response));
        }
コード例 #20
0
        public virtual ActionResult Login(LoginModel model)
        {
            var response        = new LoginResponseModel();
            var currentIdentity = GetCurrentIdentity();

            if (currentIdentity.IsAuthenticated)
            {
                // already logged in
                response.Status = ResponseStatus.AlreadyLoggedIn;
                return(JsonNetResult(response));
            }

            var id       = model != null ? model.Id : null;
            var settings = SettingsHelper.Get(id, true);

            if (!ModelState.IsValid)
            {
                if (settings.DebugMode)
                {
                    var errorList = ModelState.Values.SelectMany(m => m.Errors)
                                    .Select(e => e.ErrorMessage)
                                    .ToList();

                    Logger.Debug("Invalid login request. ModelState Errors:\n" + string.Join(". ", errorList));
                }
                return(JsonNetResult(response));
            }

            LoginOrRegister(model, settings, ref response);
            return(JsonNetResult(response));
        }
コード例 #21
0
        public async Task <LoginResponseModel> AccessLoginApi(LoginRequestModel request, Action <object> success, Action <object> failed)
        {
            LoginResponseModel resmodel = new LoginResponseModel();

            try
            {
                var    url        = string.Format("{0}/api/appconnect/AccessLogin", WebServiceDetails.BaseUri);
                string randomGuid = Guid.NewGuid().ToString();
                var    dic        = new Dictionary <string, string>();
                //dic.Add("Content-Type", "Application/json");
                dic.Add("randomguid", randomGuid);
                dic.Add("hash", randomGuid + WebServiceDetails.AppKey + request.emailaddress + request.password);
                var result   = _apiProvider.Post <LoginResponseModel, LoginRequestModel>(url, request, dic);
                var response = result.Result;
                LoginResponseModel objres = null;
                dynamic            obj    = "";
                LoginResponseModel reg    = new LoginResponseModel();
                if (response.IsSuccessful != false)
                {
                    objres = JsonConvert.DeserializeObject <LoginResponseModel>(response.RawResult);
                    success.Invoke(objres);
                }
                else
                {
                    UserDialogs.Instance.HideLoading();
                    failed.Invoke(obj);
                }
            }
            catch (Exception exception)
            {
                UserDialogs.Instance.HideLoading();
                UserDialogs.Instance.Alert("Something went wrong please try again.", "", "OK");
            }
            return(resmodel);
        }
コード例 #22
0
        public IActionResult Login([FromBody] LoginViewModel inputModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Hibás felhasználónév vagy jelszó!"));
            }

            var currentUser = _userService.getUserByName(inputModel.UserName);

            if (currentUser == null)
            {
                return(NotFound("Nincs ilyen felhasználó regisztrálva!"));
            }

            var token = new JwtTokenBuilder()
                        .AddSecurityKey(JwtSecurityKey.Create("Security key required for ShelterApp"))
                        .AddSubject(currentUser.Username)
                        .AddIssuer("ShelterServer")
                        .AddAudience("ShelterApp")
                        .AddClaim("MembershipId", currentUser.Id.ToString())
                        .AddExpiry(300)
                        .Build();

            var responseObject = new LoginResponseModel
            {
                User  = currentUser,
                Token = token.Value
            };

            return(Ok(responseObject));
        }
コード例 #23
0
        public IHttpActionResult Login(LoginModel model)
        {
            try
            {
                using (var dataContext = new HuntingEntities())
                {
                    UserSession userSession;
                    var         result = AclUserContext.LoginUser(dataContext, model.Email, model.Password, out userSession);
                    switch (result)
                    {
                    case LoginResultEnum.Error:
                        return(InternalServerError());

                    case LoginResultEnum.NotFound:
                        return(NotFound());

                    case LoginResultEnum.WrongPassword:
                        return(NotFound());

                    case LoginResultEnum.NotAllowed:
                        return(NotFound());

                    case LoginResultEnum.Success:
                        var responseModel = new LoginResponseModel(userSession);
                        return(Ok(responseModel));
                    }
                    return(NotFound());
                }
            }
            catch (Exception exception)
            {
                logger.Error(exception, "MobileController - Login, Model = {0}", (model != null ? model.Email : "N/A"));
                return(InternalServerError());
            }
        }
コード例 #24
0
        public async Task <LoginResponseModel> ValidateUser(string email, string password)
        {
            // we should go to database and get the record by email

            var dbUser = await _userRepository.GetUserByEmail(email);

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

            var hashedPassword = HashPassword(password, dbUser.Salt);

            if (hashedPassword == dbUser.HashedPassword)
            {
                // user entered correct password
                var loginUserResponse = new LoginResponseModel
                {
                    Id        = dbUser.Id,
                    FirstName = dbUser.FirstName,
                    LastName  = dbUser.LastName,
                    Email     = dbUser.Email
                };
                return(loginUserResponse);
            }

            return(null);
        }
コード例 #25
0
        public LoginResponseModel Login(LoginModel model)
        {
            LoginResponseModel response = new LoginResponseModel();

            try
            {
                var dt = user.Login(model).Tables[0];

                if (dt.Rows.Count > 0)
                {
                    response = dt.AsEnumerable().Select(x => new LoginResponseModel
                    {
                        UserName   = x.Field <string>("UserName"),
                        UserId     = x.Field <int>("UserId"),
                        RoleID     = x.Field <int>("RoleID"),
                        ServerName = x.Field <string>("ServerName"),
                        DbName     = x.Field <string>("DatabseName"),
                        DbUserName = x.Field <string>("DbUserName"),
                        Password   = x.Field <string>("Password"),
                    }).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(response);
            // return user.Login(model);
        }
コード例 #26
0
        /// <summary>
        /// Execute processing.
        /// </summary>
        /// <param name="request">RequestModel</param>
        /// <returns>ResponseModel</returns>
        private LoginResponseModel Execute(LoginRequestModel request)
        {
            // Local variable declaration
            LoginResponseModel responseModel = null;
            InitDataModel      inputObject   = null;
            InitDataModel      resultObject  = new InitDataModel();

            // Variable initialize
            responseModel = new LoginResponseModel();

            // Execute convert input.
            inputObject = Convert(request);

            // Get infomation
            UserComDao userCom = new UserComDao();
            User       result  = userCom.GetSingle(inputObject.UserName, DataHelper.GetMd5Hash(inputObject.Password));

            if (result != null)
            {
                resultObject.StatusFlag = true;
                resultObject.UserName   = result.Email;
                resultObject.UserCd     = result.UserCd.ToString();
            }
            else
            {
                resultObject.StatusFlag = false;
                throw new ExecuteException("E_MSG_00008");
            }

            // Execute convert ouput.
            responseModel = Convert(resultObject);

            return(responseModel);
        }
コード例 #27
0
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.TryGetValue(ApiKeyHeaderName, out var apiKeyHeaderValues))
            {
                return(AuthenticateResult.Fail("Missing Authorization Header"));
            }

            string refresh_token = apiKeyHeaderValues.FirstOrDefault();

            if (string.IsNullOrEmpty(refresh_token))
            {
                return(AuthenticateResult.Fail("Invalid Token"));
            }

            LoginResponseModel response = await _identityService.LoadOffTokenAsync(refresh_token);

            if (response == null || response.Id == 0)
            {
                return(AuthenticateResult.Fail("Invalid X-Token provided."));
            }

            _workContext.Handle(response);

            var claims    = new[] { new Claim(ClaimTypes.NameIdentifier, string.Empty) };
            var identity  = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket    = new AuthenticationTicket(principal, Scheme.Name);

            return(AuthenticateResult.Success(ticket));
        }
コード例 #28
0
        public async Task <LoginResponseModel> ValidateUser(string email, string password)
        {
            var user = await _userRepository.GetUserByEmailAsync(email);

            if (user == null)
            {
                // throw exception if user doesn't exist
                // throw new Exception("Please Register first");
                return(null);
            }

            var hashedPassword = _cryptoService.HashPassword(password, user.Salt);

            if (hashedPassword.Equals(user.HashedPassword))
            {
                var response = new LoginResponseModel
                {
                    Id          = user.Id,
                    Email       = user.Email,
                    DateOfBirth = user.DateOfBirth,
                    FirstName   = user.FirstName,
                    LastName    = user.LastName
                };
                return(response);
            }

            return(null);
        }
コード例 #29
0
        private void LogLoginRespondeModel(LoginResponseModel loginResponseModel, string getSetNotification)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, property notification: {getSetNotification}");

                if (loginResponseModel == null)
                {
                    _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, loginRespondeModel: is null");

                    return;
                }

                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.AccesToken)}: {loginResponseModel.AccesToken}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.Expires)}: {loginResponseModel.Expires}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.ExpiresDateTime)}: {loginResponseModel.ExpiresDateTime}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.ExpiresIn)}: {loginResponseModel.ExpiresIn}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.Issued)}: {loginResponseModel.Issued}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.IssuedDateTime)}: {loginResponseModel.IssuedDateTime}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.RefreshExpires)}: {loginResponseModel.RefreshExpires}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.RefreshExpiresDateTime)}: {loginResponseModel.RefreshExpiresDateTime}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.RefreshToken)}: {loginResponseModel.RefreshToken}");
                _logger.LogDebug($"{_classLogMessageDiagnose} {_propertyLoginMessageDiagnose}, parameter {nameof(LoginResponseModel.TokenType)}: {loginResponseModel.TokenType}");
            }
        }
コード例 #30
0
ファイル: AuthController.cs プロジェクト: Paria7/WorkflowDemo
        public ActionResult <LoginResponseModel> LoginOld([FromBody] LoginEntity entity)
        {
            LoginResponseModel model = new LoginResponseModel();

            bool loginSuccess = false;
            var  exsitsUser   = this.Repository.GetUserByName(entity.UserName);

            if (exsitsUser != null)
            {
                if (string.IsNullOrEmpty(exsitsUser.PasswordSalt))
                {
                    loginSuccess = exsitsUser.Password == entity.Password;
                }
                else
                {
                    var encryptPassword = SHA_Encrypt(entity.Password, exsitsUser.PasswordSalt);
                    loginSuccess = exsitsUser.Password == encryptPassword;
                }
            }

            if (loginSuccess)
            {
                HttpContext.SignIn(exsitsUser.Name, exsitsUser.EmployeeNo);
                model.Success = true;
                model.User    = exsitsUser;
            }
            else
            {
                model.Success = false;
                model.Message = "Username or password is invalid";
            }

            return(Ok(model));
        }
コード例 #31
0
ファイル: UserController.cs プロジェクト: velialarm/FancyApps
        public LoginResponseModel AuthenticateUser(LoginRequestModel input)
        {
            var response = new LoginResponseModel();

            if (!this.ModelState.IsValid)
            {
                var errorMessage = this.ModelState.Values.First().Errors.First().ErrorMessage;
                response.Status = new Status(102, errorMessage);
                return response;
            }

            if (input == null)
            {
                response.Status = Status.MISSING_PARRAMETERS;
                return response;
            }

            ////get user by email
            var existUser = this.Users.SingleOrDefault(a => a.Email == input.Email);
            bool isValidPassword = false;
            if (existUser != null)
            {
                isValidPassword = AuthenticationUtil.IsValidPassword(existUser.Token, input.Password);

            }
            if (!isValidPassword)
            {
                response.Status = Status.INVALID_PASSWORD;
                return response;
            }

            var recreateToken = AuthenticationUtil.Encrypt(input.Password);
            existUser.Token = recreateToken;
            if (!String.IsNullOrEmpty(input.FanApp))
            {
                existUser.FanApps = input.FanApp;
            }

            this.Users.Update(existUser);
            response.Status = Status.LOGIN_SUCCESFULLY;
            response.Token = recreateToken;
            return response;
        }
コード例 #32
0
        public HttpResponseMessage LoginUser(UserModel model)
        {
            return this.ExecuteOperationAndHandleExceptions(() =>
            {
                //this.ValidateUser(model);
                if (model == null)
                {
                    throw new FormatException("invalid username and/or password");
                }
                this.ValidateAuthCode(model.AuthCode);
                try
                {
                    this.ValidateUsername(model.Username);
                }
                catch (Exception ex)
                {
                    this.ValidateEmail(model.Email);
                }

                var context = new ApplicationDbContext();
                var username = ((string.IsNullOrEmpty(model.Username)) ? model.Email : model.Username).ToLower();
                var user = context.Users.FirstOrDefault(u => u.Username == username || u.Email == username);
                if (user == null)
                {
                    throw new InvalidOperationException("Invalid username or password");
                }
                if (user.AccessToken == null)
                {
                    user.AccessToken = this.GenerateAccessToken(user.Id);
                    context.SaveChanges();
                }
                var responseModel = new LoginResponseModel()
                {
                    Id = user.Id,
                    Username = user.Username,
                    AccessToken = user.AccessToken
                };
                var response = this.Request.CreateResponse(HttpStatusCode.OK, responseModel);
                return response;
            });
        }