Beispiel #1
0
        /// <summary>
        /// Logic to update UserAuth from Registration info, not enabled on PUT because of security.
        /// </summary>
        public object UpdateUserAuth(Register request)
        {
            if (!HostContext.AppHost.GlobalRequestFiltersAsyncArray.Contains(ValidationFilters.RequestFilterAsync)) //Already gets run
            {
                RegistrationValidator.ValidateAndThrow(request, ApplyTo.Put);
            }

            var response = ValidateFn?.Invoke(this, HttpMethods.Put, request);

            if (response != null)
            {
                return(response);
            }

            var session = this.GetSession();

            var authRepo = HostContext.AppHost.GetAuthRepository(base.Request);

            using (authRepo as IDisposable)
            {
                var existingUser = authRepo.GetUserAuth(session, null);
                if (existingUser == null)
                {
                    throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request));
                }

                var newUserAuth = ToUserAuth(authRepo, request);
                authRepo.UpdateUserAuth(existingUser, newUserAuth, request.Password);

                return(new RegisterResponse
                {
                    UserId = existingUser.Id.ToString(CultureInfo.InvariantCulture),
                });
            }
        }
        /// <summary>
        /// Logic to update UserAuth from Registration info, not enabled on PUT because of security.
        /// </summary>
        public async Task <object> UpdateUserAuthAsync(Register request)
        {
            if (!HostContext.AppHost.GlobalRequestFiltersAsyncArray.Contains(ValidationFilters.RequestFilterAsync)) //Already gets run
            {
                await RegistrationValidator.ValidateAndThrowAsync(request, ApplyTo.Put).ConfigAwait();
            }

            var response = ValidateFn?.Invoke(this, HttpMethods.Put, request);

            if (response != null)
            {
                return(response);
            }

            var session = await this.GetSessionAsync().ConfigAwait();

            var authRepo = HostContext.AppHost.GetAuthRepositoryAsync(base.Request);

#if NET472 || NETCORE
            await using (authRepo as IAsyncDisposable)
#else
            using (authRepo as IDisposable)
#endif
            {
                var existingUser = await authRepo.GetUserAuthAsync(session, null).ConfigAwait();

                if (existingUser == null)
                {
                    throw HttpError.NotFound(ErrorMessages.UserNotExists.Localize(Request));
                }

                var newUserAuth = ToUser(request);
                await authRepo.UpdateUserAuthAsync(existingUser, newUserAuth, request.Password).ConfigAwait();

                return(new RegisterResponse
                {
                    UserId = existingUser.Id.ToString(CultureInfo.InvariantCulture),
                });
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Create new Registration
        /// </summary>
        public object Post(Register request)
        {
            if (HostContext.GetPlugin <AuthFeature>()?.SaveUserNamesInLowerCase == true)
            {
                if (request.UserName != null)
                {
                    request.UserName = request.UserName.ToLower();
                }
                if (request.Email != null)
                {
                    request.Email = request.Email.ToLower();
                }
            }

            var validateResponse = ValidateFn?.Invoke(this, HttpMethods.Post, request);

            if (validateResponse != null)
            {
                return(validateResponse);
            }

            RegisterResponse response = null;
            var       session         = this.GetSession();
            bool      registerNewUser;
            IUserAuth user;

            var authRepo    = HostContext.AppHost.GetAuthRepository(base.Request);
            var newUserAuth = ToUserAuth(authRepo, request);

            using (authRepo as IDisposable)
            {
                var existingUser = session.IsAuthenticated ? authRepo.GetUserAuth(session, null) : null;
                registerNewUser = existingUser == null;

                if (!registerNewUser && !AllowUpdates)
                {
                    throw new NotSupportedException(ErrorMessages.RegisterUpdatesDisabled.Localize(Request));
                }

                if (!HostContext.AppHost.GlobalRequestFiltersAsyncArray.Contains(ValidationFilters.RequestFilterAsync)) //Already gets run
                {
                    RegistrationValidator?.ValidateAndThrow(request, registerNewUser ? ApplyTo.Post : ApplyTo.Put);
                }

                user = registerNewUser
                    ? authRepo.CreateUserAuth(newUserAuth, request.Password)
                    : authRepo.UpdateUserAuth(existingUser, newUserAuth, request.Password);

                if (request.AutoLogin.GetValueOrDefault())
                {
                    using (var authService = base.ResolveService <AuthenticateService>())
                    {
                        var authResponse = authService.Post(
                            new Authenticate {
                            provider = CredentialsAuthProvider.Name,
                            UserName = request.UserName ?? request.Email,
                            Password = request.Password,
                            Continue = request.Continue ?? base.Request.GetQueryStringOrForm(Keywords.ReturnUrl)
                        });

                        if (authResponse is IHttpError)
                        {
                            throw (Exception)authResponse;
                        }

                        if (authResponse is AuthenticateResponse typedResponse)
                        {
                            response = new RegisterResponse
                            {
                                SessionId    = typedResponse.SessionId,
                                UserName     = typedResponse.UserName,
                                ReferrerUrl  = typedResponse.ReferrerUrl,
                                UserId       = user.Id.ToString(CultureInfo.InvariantCulture),
                                BearerToken  = typedResponse.BearerToken,
                                RefreshToken = typedResponse.RefreshToken,
                            };
                        }
                    }
                }

                if (registerNewUser)
                {
                    session = this.GetSession();
                    if (!request.AutoLogin.GetValueOrDefault())
                    {
                        session.PopulateSession(user, authRepo);
                    }

                    session.OnRegistered(Request, session, this);
                    AuthEvents?.OnRegistered(this.Request, session, this);
                }
            }

            if (response == null)
            {
                response = new RegisterResponse
                {
                    UserId      = user.Id.ToString(CultureInfo.InvariantCulture),
                    ReferrerUrl = request.Continue,
                    UserName    = session.UserName,
                };
            }

            var isHtml = Request.ResponseContentType.MatchesContentType(MimeTypes.Html);

            if (isHtml)
            {
                if (string.IsNullOrEmpty(request.Continue))
                {
                    return(response);
                }

                return(new HttpResult(response)
                {
                    Location = request.Continue
                });
            }

            return(response);
        }
        /// <summary>
        /// Create new Registration
        /// </summary>
        public async Task <object> PostAsync(Register request)
        {
            var authFeature = GetPlugin <AuthFeature>();

            if (authFeature != null)
            {
                if (authFeature.SaveUserNamesInLowerCase)
                {
                    if (request.UserName != null)
                    {
                        request.UserName = request.UserName.ToLower();
                    }
                    if (request.Email != null)
                    {
                        request.Email = request.Email.ToLower();
                    }
                }
            }

            var validateResponse = ValidateFn?.Invoke(this, HttpMethods.Post, request);

            if (validateResponse != null)
            {
                return(validateResponse);
            }

            var session = await this.GetSessionAsync().ConfigAwait();

            var newUserAuth = ToUser(request);

            var existingUser = session.IsAuthenticated
                ? await AuthRepositoryAsync.GetUserAuthAsync(session, null).ConfigAwait()
                : null;

            var registerNewUser = existingUser == null;

            if (!registerNewUser && !AllowUpdates)
            {
                throw new NotSupportedException(ErrorMessages.RegisterUpdatesDisabled.Localize(Request));
            }

            var runValidation = !HostContext.AppHost.GlobalRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsync) && //Already gets run
                                RegistrationValidator != null;

            if (registerNewUser)
            {
                if (runValidation)
                {
                    await ValidateAndThrowAsync(request);
                }
                var user = await AuthRepositoryAsync.CreateUserAuthAsync(newUserAuth, request.Password).ConfigAwait();
                await RegisterNewUserAsync(session, user).ConfigAwait();
            }
            else
            {
                if (runValidation)
                {
                    await RegistrationValidator.ValidateAndThrowAsync(request, ApplyTo.Put).ConfigAwait();
                }
                var user = await AuthRepositoryAsync.UpdateUserAuthAsync(existingUser, newUserAuth, request.Password).ConfigAwait();
            }

            var response = await CreateRegisterResponse(session,
                                                        request.UserName ?? request.Email, request.Password, request.AutoLogin);

            return(response);
        }
Beispiel #5
0
        /// <summary>
        /// Create new Registration
        /// </summary>
        public object Post(Register request)
        {
            var validateRes = ValidateFn?.Invoke(this, Request.Verb, request);

            if (validateRes != null)
            {
                return(validateRes);
            }

            bool      registerNewUser;
            IUserAuth user;
            var       session     = this.GetSession();
            var       newUserAuth = ConvertToUserAuth(request);

            using (AuthRepository as IDisposable)
            {
                var existingUser = session.IsAuthenticated ? AuthRepository.GetUserAuth(session, null) : null;
                registerNewUser = existingUser == null;

                if (!HostContext.AppHost.GlobalMessageRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsync)) //Already gets run
                {
                    if (RegistrationValidator is IRequiresRequest)
                    {
                        ((IRequiresRequest)RegistrationValidator).Request = base.Request;
                    }

                    RegistrationValidator?.ValidateAndThrow(request, registerNewUser ? ApplyTo.Post : ApplyTo.Put);
                }

                if (!registerNewUser && !AllowUpdates)
                {
                    throw new NotSupportedException(ErrorMessages.RegisterUpdatesDisabled.Localize(Request));
                }

                user = registerNewUser
                    ? AuthRepository.CreateUserAuth(newUserAuth, request.Password)
                    : AuthRepository.UpdateUserAuth(existingUser, newUserAuth, request.Password);
            }
            RegisterResponse responseDto = new RegisterResponse {
                UserId      = user.Id.ToString(CultureInfo.InvariantCulture),
                ReferrerUrl = request.Continue
            };
            AuthenticateService authService;

            if (request.AutoLogin && (authService = base.ResolveService <AuthenticateService>()) != null)
            {
                object authResponse;
                using (authService)
                {
                    authResponse = authService.Post(
                        new Authenticate {
                        Provider = CredentialsAuthProvider.Name,
                        UserName = request.UserName ?? request.Email,
                        Password = request.Password,
                        Continue = request.Continue
                    });
                }
                if (authResponse is Exception)
                {
                    throw (Exception)authResponse;
                }

                if (authResponse is AuthenticateResponse typedResponse)
                {
                    responseDto = new RegisterResponse
                    {
                        SessionId    = typedResponse.SessionId,
                        UserName     = typedResponse.UserName,
                        ReferrerUrl  = typedResponse.ReferrerUrl,
                        UserId       = user.Id.ToString(CultureInfo.InvariantCulture),
                        BearerToken  = typedResponse.BearerToken,
                        RefreshToken = typedResponse.RefreshToken,
                    };
                }
            }

            if (registerNewUser)
            {
                session = this.GetSession();
                if (!request.AutoLogin)
                {
                    session.PopulateSession(user, new List <IAuthTokens>());
                }

                session.OnRegistered(Request, session, this);
                AuthEvents?.OnRegistered(Request, session, this);
            }
            if (Request.ResponseContentType.MatchesContentType(MimeTypes.Html))
            {
                if (request.Continue.IsNullOrEmpty())
                {
                    return(responseDto);
                }

                return(new HttpResult(responseDto)
                {
                    Location = request.Continue
                });
            }
            return(responseDto);
        }
        /// <summary>
        ///     Create new Registration
        /// </summary>
        public async Task <object> Post(Register request)
        {
            var returnUrl = Request.GetReturnUrl();

            var authFeature = GetPlugin <AuthFeature>();

            if (authFeature != null)
            {
                if (authFeature.SaveUserNamesInLowerCase == true)
                {
                    if (request.UserName != null)
                    {
                        request.UserName = request.UserName.ToLower();
                    }
                    if (request.Email != null)
                    {
                        request.Email = request.Email.ToLower();
                    }
                }
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    authFeature.ValidateRedirectLinks(Request, returnUrl);
                }
            }

            var validateResponse = ValidateFn?.Invoke(this, HttpMethods.Post, request);

            if (validateResponse != null)
            {
                return(validateResponse);
            }

            RegisterResponse response = null;
            var session = await this.GetSessionAsync();

            var newUserAuth = ToUserAuth(AuthRepositoryAsync as ICustomUserAuth, request);

            var existingUser = session.IsAuthenticated
                ? await AuthRepositoryAsync.GetUserAuthAsync(session, null).ConfigAwait()
                : null;

            var registerNewUser = existingUser == null;

            if (!registerNewUser && !AllowUpdates)
            {
                throw new NotSupportedException(ErrorMessages.RegisterUpdatesDisabled.Localize(Request));
            }

            if (!HostContext.AppHost.GlobalRequestFiltersAsync.Contains(ValidationFilters.RequestFilterAsync) && //Already gets run
                RegistrationValidator != null)
            {
                await RegistrationValidator.ValidateAndThrowAsync(request, registerNewUser?ApplyTo.Post : ApplyTo.Put).ConfigAwait();
            }

            var user = registerNewUser
                ? await AuthRepositoryAsync.CreateUserAuthAsync(newUserAuth, request.Password).ConfigAwait()
                : await AuthRepositoryAsync.UpdateUserAuthAsync(existingUser, newUserAuth, request.Password).ConfigAwait();

            if (registerNewUser)
            {
                session.PopulateSession(user);
                session.OnRegistered(Request, session, this);
                AuthEvents?.OnRegistered(this.Request, session, this);
            }

            if (request.AutoLogin.GetValueOrDefault())
            {
                using (var authService = base.ResolveService <AuthenticateService>())
                {
                    var authResponse = await authService.Post(
                        new Authenticate {
                        provider = CredentialsAuthProvider.Name,
                        UserName = request.UserName ?? request.Email,
                        Password = request.Password,
                    });

                    if (authResponse is IHttpError)
                    {
                        throw (Exception)authResponse;
                    }

                    if (authResponse is AuthenticateResponse typedResponse)
                    {
                        response = new RegisterResponse
                        {
                            SessionId    = typedResponse.SessionId,
                            UserName     = typedResponse.UserName,
                            ReferrerUrl  = typedResponse.ReferrerUrl,
                            UserId       = user.Id.ToString(CultureInfo.InvariantCulture),
                            BearerToken  = typedResponse.BearerToken,
                            RefreshToken = typedResponse.RefreshToken,
                        };
                    }
                }
            }

            if (response == null)
            {
                response = new RegisterResponse
                {
                    UserId      = user.Id.ToString(CultureInfo.InvariantCulture),
                    ReferrerUrl = Request.GetReturnUrl(),
                    UserName    = session.UserName,
                };
            }

            var isHtml = Request.ResponseContentType.MatchesContentType(MimeTypes.Html);

            if (isHtml)
            {
                if (string.IsNullOrEmpty(returnUrl))
                {
                    return(response);
                }

                return(new HttpResult(response)
                {
                    Location = returnUrl
                });
            }

            return(response);
        }