Example #1
0
        public async Task <IActionResult> OnPost(Business.Models.LoginModel model,
                                                 string return_url = Routing.DASHBOARD)
        {
            SetPageInfo();
            //this is auto handled by anti-forgery: return 400 bad request
            if (User.Identity.IsAuthenticated)
            {
                Message      = "Bạn chỉ được đăng nhập cùng lúc 1 tài khoản";
                MessageTitle = "Đã đăng nhập";
                return(this.MessageView());
            }
            var entity = await identityService.AuthenticateAsync(model.username, model.password);

            if (entity != null)
            {
                #region Custom Signin for extra claims store
                var principal = await identityService.GetApplicationPrincipalAsync(entity);

                var utcNow      = DateTime.UtcNow;
                var cookieProps = new AuthenticationProperties()
                {
                    IssuedUtc = utcNow,
                };
                if (model.remember_me)
                {
                    cookieProps.IsPersistent = true;
                    cookieProps.ExpiresUtc   = utcNow.AddHours(Settings.Instance.CookiePersistentHours);
                }
                await HttpContext.SignInAsync(principal.Identity.AuthenticationType,
                                              principal, cookieProps);

                #endregion
                _logger.CustomProperties(entity).Info("Login user");
                #region Generate token
                var identity =
                    await identityService.GetIdentityAsync(entity, JwtBearerDefaults.AuthenticationScheme);

                principal = new ClaimsPrincipal(identity);
                var props = new AuthenticationProperties()
                {
                    IssuedUtc  = utcNow,
                    ExpiresUtc = utcNow.AddHours(WebAdmin.Settings.Instance.TokenValidHours)
                };
                props.Parameters["refresh_expires"] = utcNow.AddHours(
                    WebAdmin.Settings.Instance.RefreshTokenValidHours);
                var resp = identityService.GenerateTokenResponse(principal, props);
                #endregion
                return(LocalRedirect($"{Routing.INDEX}?access_token=" +
                                     $"{resp.access_token}" +
                                     $"&refresh_token={resp.refresh_token}" +
                                     $"&expires_utc={resp.expires_utc}" +
                                     $"&issued_utc={resp.issued_utc}" +
                                     $"&token_type={resp.token_type}&" +
                                     $"&return_url={return_url}"));
            }
            Message = "Tài khoản hoặc mật khẩu không hợp lệ";
            return(Page());
        }
Example #2
0
        /// <summary>
        /// Authenticates the credentials provided in <see cref="AuthenticationRequest"/> with the OpenStack Identity
        /// Service V2.
        /// </summary>
        /// <remarks>
        /// <para>This method caches the authentication result, and returns the cached result of a previous
        /// authentication request when possible to avoid unnecessary calls to the Identity API. If a cached
        /// authentication result is available but has either expired or will expire soon (see
        /// <see cref="ExpirationOverlap"/>), the cached result is discarded and the credentials are re-authenticated
        /// with the Identity Service.</para>
        /// </remarks>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> that the task will observe.</param>
        /// <returns>
        /// A <see cref="Task"/> representing the asynchronous operation. When the task completes successfully, the
        /// <see cref="Task{TResult}.Result"/> property will contain an <see cref="Access"/> instance providing the
        /// authentication result.
        /// </returns>
        /// <exception cref="HttpWebException">
        /// If an error occurs during an HTTP request as part of authenticating with the Identity API.
        /// </exception>
        protected virtual Task <Access> AuthenticateAsync(CancellationToken cancellationToken)
        {
            Access access = Access;

            if (access != null && access.Token != null)
            {
                Token token = access.Token;
                // Note: this code uses lifting to null to cover the case where token.ExpiresAt is null
                DateTimeOffset?effectiveExpiration = token.ExpiresAt - ExpirationOverlap;
                if (effectiveExpiration > DateTimeOffset.Now)
                {
                    return(CompletedTask.FromResult(access));
                }
            }

            return
                (IdentityService.AuthenticateAsync(AuthenticationRequest, cancellationToken)
                 .Select(
                     task =>
            {
                _access = task.Result;
                return task.Result;
            }));
        }
Example #3
0
        public async Task <IActionResult> LogIn(AuthorizationGrantModel model)
        {
            var validationData = _service.ValidateLogin(User, model);

            if (!validationData.IsValid)
            {
                return(BadRequest(AppResult.FailValidation(data: validationData)));
            }
            AppUser entity;

            switch (model.grant_type)
            {
            case "password":
            case null:
            {
                entity = await
                         _service.AuthenticateAsync(model.username, model.password);

                if (entity == null)
                {
                    return(Unauthorized(AppResult
                                        .Unauthorized(mess: "Invalid username or password")));
                }
            }
            break;

            case "refresh_token":
            {
                var validResult = _service.ValidateRefreshToken(model.refresh_token);
                if (validResult == null)
                {
                    return(Unauthorized(AppResult
                                        .Unauthorized(mess: "Invalid refresh token")));
                }
                entity = await _service.GetUserByIdAsync(validResult.Identity.Name);

                if (entity == null)
                {
                    return(Unauthorized(AppResult
                                        .Unauthorized(mess: "Invalid user identity")));
                }
            }
            break;

            case "firebase_token":
            {
                FirebaseToken validResult = await _service.ValidateFirebaseToken(model.firebase_token);

                if (validResult == null)
                {
                    return(Unauthorized(AppResult
                                        .Unauthorized(mess: "Invalid Firebase token")));
                }
                UserRecord userRecord = await FirebaseAuth.DefaultInstance.GetUserAsync(validResult.Uid);

                bool checkEmailDomain = _service.ValidateEmailDomain(userRecord.Email);
                if (!checkEmailDomain)
                {
                    return(Unauthorized(AppResult.InvalidEmailDomain()));
                }
                entity = await _service.GetUserByEmailAsync(userRecord.Email);

                var userExisted = entity != null;
                if (!userExisted || !entity.LoggedIn)
                {
                    using (var transaction = context.Database.BeginTransaction())
                    {
                        Member memberEntity;
                        if (!userExisted)
                        {
                            var emailInfo = userRecord.Email.GetEmailInfo();
                            entity = _service.ConvertToUser(userRecord, emailInfo.Item3);
                            var result = await _service
                                         .CreateUserWithoutPassAsync(entity);

                            if (!result.Succeeded)
                            {
                                foreach (var err in result.Errors)
                                {
                                    ModelState.AddModelError(err.Code, err.Description);
                                }
                                var builder = ResultHelper.MakeInvalidAccountRegistrationResults(ModelState);
                                return(BadRequest(builder));
                            }
                            _logger.CustomProperties(entity).Info("Register new user");
                            memberEntity = _memberService.ConvertToMember(entity, entity.MemberCode);
                            memberEntity = _memberService.CreateMember(memberEntity);
                        }
                        else
                        {
                            entity = _service.UpdateUser(entity, userRecord);
                            var result = await _service.UpdateUserAsync(entity);

                            if (!result.Succeeded)
                            {
                                foreach (var err in result.Errors)
                                {
                                    ModelState.AddModelError(err.Code, err.Description);
                                }
                                var builder = ResultHelper.MakeInvalidAccountRegistrationResults(ModelState);
                                return(BadRequest(builder));
                            }
                            memberEntity = _memberService.Members.Id(entity.Id).FirstOrDefault();
                            memberEntity = _memberService.UpdateMember(memberEntity, entity);
                        }
                        //log event
                        var ev = _sysService.GetEventForNewUser(
                            $"{memberEntity.Email} has logged into system for the first time",
                            memberEntity.UserId);
                        _sysService.CreateAppEvent(ev);
                        //end log event
                        context.SaveChanges();
                        transaction.Commit();
                    }
                }
            }
            break;

            default:
                return(BadRequest(AppResult.Unsupported("Unsupported grant type")));
            }
            var identity =
                await _service.GetIdentityAsync(entity, JwtBearerDefaults.AuthenticationScheme);

            var principal = new ClaimsPrincipal(identity);
            var utcNow    = DateTime.UtcNow;
            var props     = new AuthenticationProperties()
            {
                IssuedUtc  = utcNow,
                ExpiresUtc = utcNow.AddHours(WebApi.Settings.Instance.TokenValidHours)
            };

            props.Parameters["refresh_expires"] = utcNow.AddHours(
                WebApi.Settings.Instance.RefreshTokenValidHours);
            var resp = _service.GenerateTokenResponse(principal, props, model.scope ?? AppOAuthScope.ROLES);

            _logger.CustomProperties(entity).Info("Login user");
            return(Ok(resp));
        }
Example #4
0
        public async Task <IActionResult> LogIn([FromForm] AuthorizationGrantModel model)
        {
            var validationResult = _service.ValidateLogin(User, model);

            if (!validationResult.Valid)
            {
                return(BadRequest(validationResult.Result));
            }
            AppUser entity = null;

            switch (model.grant_type)
            {
            case "password":
            case null:
            {
                entity = await
                         _service.AuthenticateAsync(model.username, model.password);

                if (entity == null)
                {
                    return(Unauthorized(new AppResultBuilder()
                                        .Unauthorized(mess: "Invalid username or password")));
                }
            }
            break;

            case "refresh_token":
            {
                var validResult = _service.ValidateRefreshToken(model.refresh_token);
                if (validResult == null)
                {
                    return(Unauthorized(new AppResultBuilder()
                                        .Unauthorized(mess: "Invalid refresh token")));
                }
                entity = await _service.GetUserByIdAsync(validResult.Identity.Name);

                if (entity == null)
                {
                    return(Unauthorized(new AppResultBuilder()
                                        .Unauthorized(mess: "Invalid user identity")));
                }
            }
            break;

            default:
                return(BadRequest(new AppResultBuilder()
                                  .Unsupported("Unsupported grant type")));
            }
            var identity =
                await _service.GetIdentityAsync(entity, JwtBearerDefaults.AuthenticationScheme);

            var principal = new ClaimsPrincipal(identity);
            var utcNow    = DateTime.UtcNow;
            var props     = new AuthenticationProperties()
            {
                IssuedUtc  = utcNow,
                ExpiresUtc = utcNow.AddHours(WebApi.Settings.Instance.TokenValidHours)
            };

            props.Parameters["refresh_expires"] = utcNow.AddHours(
                WebApi.Settings.Instance.RefreshTokenValidHours);
            var resp = _service.GenerateTokenResponse(principal, props, model.scope);

            _logger.CustomProperties(entity).Info("Login user");
            if (principal.IsInRole(RoleName.Device))
            {
                if (model.fcm_token == null)
                {
                    return(BadRequest(new AppResultBuilder()
                                      .FailValidation(mess: "FCM Token is required for device login")));
                }
                using (var trans = context.Database.BeginTransaction())
                {
                    var device      = _deviceService.Devices.Id(entity.Id).FirstOrDefault();
                    var oldFcmToken = device.CurrentFcmToken;
                    _deviceService.ChangeDeviceToken(device, model.fcm_token, resp.access_token);
                    context.SaveChanges();
                    _service.LoginDevice(device, oldFcmToken, model.fcm_token);
                    trans.Commit();
                }
            }
            return(Ok(resp));
        }