コード例 #1
0
        private async Task <object> RefreshToken(string email, ApplicationUser modelUser)
        {
            var responseModel = new SumProfileResponseDTO();

            responseModel.Profile       = new ProfileReponse();
            responseModel.ListRole      = new List <ListRole>();
            responseModel.Profile.Email = email;
            //Check exists User
            var user = await _userManager.FindByNameAsync(email);

            if (user != null)
            {
                var aspNetUserLogin =
                    _repositoryWrapper.AspNetUserProfiles.FirstOrDefault(p => p.UserId == user.Id);
                responseModel.Profile                 = _mapper.Map <ProfileReponse>(user);
                responseModel.Profile.FullName        = aspNetUserLogin.FullName;
                responseModel.Profile.RegType         = aspNetUserLogin.RegType;
                responseModel.Profile.AvartarFileName = aspNetUserLogin.AvatarUrl ?? "noimage.png";
                responseModel.Profile.AvartarFullUrl  =
                    _configuration["Cloud_Path"] + $"/user/avatar/original/{aspNetUserLogin.AvatarUrl ?? "noimage.png"}";

                //List Role
                var lstRole = await _repositoryWrapper.AspNetUsers.GetListRole(user.Id);

                responseModel.ListRole = _mapper.Map <List <ListRole> >(lstRole);
                //ProductBrandId
                var userProfiler = await _repositoryWrapper.AspNetUserProfiles.FirstOrDefaultAsync(p => p.UserId == user.Id);

                if (userProfiler != null)
                {
                    responseModel.ProductBrandId = userProfiler.ProductBrand_ID ?? 0;
                }
                else
                {
                    responseModel.ProductBrandId = 0;
                }
                // responseModel.Role = lstRole.Count > 0 ? string.Join(",", lstRole) : "";
                var jwt = await GenerateJwtToken(email, modelUser);

                responseModel.JWT       = jwt.ToString();
                responseModel.UserId    = user.Id;
                responseModel.ErrorCode = "00";
                responseModel.Message   = "Đăng nhập thành công";
                //Total UnRead
                responseModel.NumberFCMUnread = await _repositoryWrapper.FCMMessage.GetNumberFCMUnread(user.Id);
            }
            return(responseModel);
        }
コード例 #2
0
        public async Task <SumProfileResponseDTO> Login(LoginDto model)
        {
            var    output        = new SumProfileResponseDTO();
            string apiUrl        = "/api/v1/Account/Login";
            var    json          = JsonConvert.SerializeObject(model, Formatting.Indented);
            var    stringContent = new StringContent(json, Encoding.UTF8, "application/json");
            var    response      = await _client.PostAsync(apiUrl, stringContent);

            if (response.IsSuccessStatusCode)
            {
                string responseStream = await response.Content.ReadAsStringAsync();

                output = JsonConvert.DeserializeObject <SumProfileResponseDTO>(responseStream);
            }
            return(output);
        }
コード例 #3
0
ファイル: AccountController.cs プロジェクト: war-man/DaNBVQ
        public async Task <JsonResult> Login([FromBody] LoginDto model, string returnUrl = "/")
        {
            var output = new SumProfileResponseDTO();

            try
            {
                output = await _repoWrapper.Account.Login(model);

                if (output.ErrorCode == "00")
                {
                    Response.Cookies.Append("JWT", JsonConvert.SerializeObject(output));
                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.Name, output.Profile.UserName),
                        new Claim("UserInfomation", JsonConvert.SerializeObject(output)),
                        new Claim("access_token", output.JWT)
                    };

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

                    var authProperties = new AuthenticationProperties
                    {
                        //AllowRefresh = <bool>,
                        // Refreshing the authentication session should be allowed.

                        ExpiresUtc = DateTimeOffset.UtcNow.AddHours(10),
                        // The time at which the authentication ticket expires. A
                        // value set here overrides the ExpireTimeSpan option of
                        // CookieAuthenticationOptions set with AddCookie.

                        IsPersistent = true,
                        // Whether the authentication session is persisted across
                        // multiple requests. When used with cookies, controls
                        // whether the cookie's lifetime is absolute (matching the
                        // lifetime of the authentication ticket) or session-based.

                        //IssuedUtc = <DateTimeOffset>,
                        // The time at which the authentication ticket was issued.

                        //RedirectUri = <string>
                        // The full path or absolute URI to be used as an http
                        // redirect response value.
                    };

                    await HttpContext.SignInAsync(
                        CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity),
                        authProperties);
                }
                else
                {
                    _logger.LogInformation($"Account Controller - Login Fail {JsonConvert.SerializeObject(model)}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"AccountController - Login {ex.ToString()}");
            }
            return(Json(JsonConvert.SerializeObject(output)));
        }
コード例 #4
0
        public async Task <object> Login([FromBody] LoginDto model)
        {
            //var username = principal.Identity.Name; //this is mapped to the Name claim by default

            var responseModel = new SumProfileResponseDTO();

            responseModel.Profile       = new ProfileReponse();
            responseModel.ListRole      = new List <ListRole>();
            responseModel.Profile.Email = model.Email;
            var inputUserName = model.Email;
            var inputEmail    = model.Email;

            if (Util.IsPhoneNumber(model.Email))
            {
                model.Email = $"{model.Email}@hanoma.vn";
            }
            //Check input Email Pass
            if (String.IsNullOrEmpty(model.Email) || String.IsNullOrEmpty(model.Password))
            {
                responseModel.ErrorCode = "ACC006";
                responseModel.Message   = ConstMessage.GetMsgConst("ACC006");
                return(responseModel);
            }
            else
            {
                //Check exists User
                var user = await _userManager.FindByNameAsync(inputUserName);

                if (user != null)
                {
                    var result = await _signInManager.PasswordSignInAsync(inputUserName, model.Password, false, false);

                    if (result.Succeeded)
                    {
                        //var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
                        var aspNetUserLogin =
                            _repositoryWrapper.AspNetUserProfiles.FirstOrDefault(p => p.UserId == user.Id);
                        responseModel.Profile                 = _mapper.Map <ProfileReponse>(user);
                        responseModel.Profile.FullName        = aspNetUserLogin.FullName;
                        responseModel.Profile.RegType         = aspNetUserLogin.RegType;
                        responseModel.Profile.AvartarFileName = aspNetUserLogin.AvatarUrl ?? "noimage.png";
                        responseModel.Profile.AvartarFullUrl  =
                            _configuration["Cloud_Path"] + $"/user/avatar/original/{aspNetUserLogin.AvatarUrl ?? "noimage.png"}";

                        //List Role
                        var lstRole = await _repositoryWrapper.AspNetUsers.GetListRole(user.Id);

                        responseModel.ListRole = _mapper.Map <List <ListRole> >(lstRole);
                        //ProductBrandId
                        var userProfiler = await _repositoryWrapper.AspNetUserProfiles.FirstOrDefaultAsync(p => p.UserId == user.Id);

                        if (userProfiler != null)
                        {
                            responseModel.ProductBrandId = userProfiler.ProductBrand_ID ?? 0;
                            if (responseModel.ProductBrandId != 0)
                            {
                                var brand = await _repositoryWrapper.Brand.FirstOrDefaultAsync(p => p.ProductBrand_ID == responseModel.ProductBrandId);

                                if (brand != null)
                                {
                                    responseModel.ProductBrandTypeId    = brand.ProductBrandType_ID ?? 1;
                                    responseModel.ProductBrandYearJoin  = (int)(DateTime.Now.Year - brand.CreateDate?.Year);
                                    responseModel.ReferralCode          = brand.ReferralCode;
                                    responseModel.ProductBrandName      = brand.Name;
                                    responseModel.ProductBrandAvatarUrl = _configuration["Cloud_Path"] + $"/productbrand/logo/original/{brand.Logo}";
                                }
                            }
                        }
                        else
                        {
                            responseModel.ProductBrandId = 0;
                        }
                        // responseModel.Role = lstRole.Count > 0 ? string.Join(",", lstRole) : "";
                        var jwt = await GenerateJwtToken(inputUserName, user);

                        responseModel.JWT       = jwt.ToString();
                        responseModel.UserId    = user.Id;
                        responseModel.ErrorCode = "00";
                        responseModel.Message   = "Đăng nhập thành công";
                        //Total UnRead
                        responseModel.NumberFCMUnread = await _repositoryWrapper.FCMMessage.GetNumberFCMUnread(user.Id);

                        return(responseModel);
                    }
                    // After register must verify
                    if (result.IsNotAllowed)
                    {
                        responseModel.ErrorCode = "ACC013";
                        responseModel.Message   = ConstMessage.GetMsgConst("ACC013");
                        return(responseModel);
                    }
                    //Yêu cầu xác  thực mỗi lần đăng nhập
                    if (result.RequiresTwoFactor)
                    {
                        responseModel.ErrorCode = "ACC013";
                        responseModel.Message   = ConstMessage.GetMsgConst("ACC013");
                        return(responseModel);
                    }
                    if (result.IsLockedOut)
                    {
                        responseModel.ErrorCode = "ACC011";
                        responseModel.Message   = ConstMessage.GetMsgConst("ACC011");
                        return(responseModel);
                    }
                    else
                    {
                        _logger.LogError($"[AccountController] Mật khẩu không đúng!");
                        responseModel.ErrorCode = "ACC007";
                        responseModel.Message   = ConstMessage.GetMsgConst("ACC007");
                        return(responseModel);
                    }
                }

                else
                {
                    _logger.LogError($"[AccountController] Tài khoản {model.Email} không tồn tại");
                    responseModel.ErrorCode = "ACC008";
                    responseModel.Message   = ConstMessage.GetMsgConst("ACC008");
                    return(responseModel);
                }
            }
        }
コード例 #5
0
        public async Task <object> LoginByJWT([FromBody] LoginTokenDTO model)
        {
            var responseModel = new SumProfileResponseDTO();

            responseModel.Profile       = new ProfileReponse();
            responseModel.ListRole      = new List <ListRole>();
            responseModel.Profile.Email = model.Email;
            if (model.Jwt == null)
            {
                responseModel.ErrorCode = "001";
                responseModel.Message   = "Token không hợp lệ";
            }
            else
            {
                CheckExpireToken response = await GetPrincipalFromExpiredToken(model.Jwt);

                if (response.ErrorCode == "00")
                {
                    //Check exists User
                    var user = await _userManager.FindByNameAsync(response.Email);

                    if (user != null)
                    {
                        var aspNetUserLogin =
                            _repositoryWrapper.AspNetUserProfiles.FirstOrDefault(p => p.UserId == user.Id);
                        responseModel.Profile                 = _mapper.Map <ProfileReponse>(user);
                        responseModel.Profile.FullName        = aspNetUserLogin.FullName;
                        responseModel.Profile.RegType         = aspNetUserLogin.RegType;
                        responseModel.Profile.AvartarFileName = aspNetUserLogin.AvatarUrl ?? "noimage.png";
                        responseModel.Profile.AvartarFullUrl  =
                            _configuration["Cloud_Path"] + $"/user/avatar/original/{aspNetUserLogin.AvatarUrl ?? "noimage.png"}";

                        //List Role
                        var lstRole = await _repositoryWrapper.AspNetUsers.GetListRole(user.Id);

                        responseModel.ListRole = _mapper.Map <List <ListRole> >(lstRole);
                        //ProductBrandId
                        var userProfiler = await _repositoryWrapper.AspNetUserProfiles.FirstOrDefaultAsync(p => p.UserId == user.Id);

                        if (userProfiler != null)
                        {
                            responseModel.ProductBrandId = userProfiler.ProductBrand_ID ?? 0;
                            if (responseModel.ProductBrandId != 0)
                            {
                                var brand = await _repositoryWrapper.Brand.FirstOrDefaultAsync(p => p.ProductBrand_ID == responseModel.ProductBrandId);

                                if (brand != null)
                                {
                                    responseModel.ProductBrandTypeId   = brand.ProductBrandType_ID ?? 1;
                                    responseModel.ProductBrandYearJoin = (int)(DateTime.Now.Year - brand.CreateDate?.Year);
                                    responseModel.ReferralCode         = brand.ReferralCode;
                                }
                            }
                        }
                        else
                        {
                            responseModel.ProductBrandId = 0;
                        }

                        // responseModel.Role = lstRole.Count > 0 ? string.Join(",", lstRole) : "";
                        //var jwt = await GenerateJwtToken(model.Email, user);
                        responseModel.JWT       = model.Jwt;
                        responseModel.UserId    = user.Id;
                        responseModel.ErrorCode = "00";
                        responseModel.Message   = "Đăng nhập thành công";
                        //Total UnRead
                        responseModel.NumberFCMUnread = await _repositoryWrapper.FCMMessage.GetNumberFCMUnread(user.Id);

                        return(responseModel);
                    }
                }
                else if (response.ErrorCode == "003")
                {
                    //Call refresh token
                    var user = await _userManager.FindByNameAsync(model.Email);

                    if (user != null)
                    {
                        return(await RefreshToken(model.Email, user));
                    }
                    else
                    {
                        responseModel.ErrorCode = response.ErrorCode;
                        responseModel.Message   = response.Message;
                    }
                }
                else
                {
                    responseModel.ErrorCode = response.ErrorCode;
                    responseModel.Message   = response.Message;
                }
            }
            return(responseModel);
        }