Exemplo n.º 1
0
        /// <summary>
        /// Enregistre un nouvel <see cref="User"/>.
        /// </summary>
        /// <param name="model">L'<see cref="User"/> a créé.</param>
        /// <returns>L'utilisateur créé.</returns>
        public User Register(User model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            // Le nom d'utilisateur doit être unique.
            if (this.GetByUsername(model.Username) != null)
            {
                throw new ArgumentException((this as ILocalizedService <UserService>).GetLocalized("RegisterErrorUserUsernameAlreadyExists", model.Username));
            }

            // L'email doit être unique.
            else if (this.GetByEmail(model.Email) != null)
            {
                throw new ArgumentException((this as ILocalizedService <UserService>).GetLocalized("RegisterErrorUserEmailAlreadyExists", model.Email));
            }

            model.ActivationToken = CryptographicHelper.GetUrlSafeToken(24);
            model.Active          = false;

            return(this.Create(model)?.WithoutPassword());
        }
        public IActionResult ForgotPassword([FromBody] UserPasswordLostModel model)
        {
            this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenTry"].Value));

            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            User user = null;

            if (!string.IsNullOrEmpty(model.Email))
            {
                user = this.userService.GetByEmail(model.Email);
            }
            else if (!string.IsNullOrEmpty(model.Username))
            {
                user = this.userService.GetByUsername(model.Username);
            }

            if (user == null)
            {
                this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenUserNotFound"].Value, new { method = !string.IsNullOrEmpty(model.Email) ? "email" : "username", value = model.Email ?? model.Username }));
                return(this.NotFound(new { message = string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenUserNotFound"].Value) }));
            }

            UserPasswordResetToken userPasswordResetToken;
            string token;

            try
            {
                token = CryptographicHelper.GetUrlSafeToken(24);
                userPasswordResetToken = new UserPasswordResetToken()
                {
                    Token      = token,
                    ValidUntil = DateTime.UtcNow.AddMinutes(this.appSettings.Security.ResetPasswordTokenDurationInMinutes),
                    Created    = DateTime.UtcNow,
                    CreatedBy  = new UserReference()
                    {
                        Id = user.Id, Username = user.Username
                    },
                };
                userPasswordResetToken = this.userPasswordResetTokenService.Create(userPasswordResetToken);

                // Sending reset password email, with token in clear value.
                this.emailService.SendTemplate(new EmailAddress()
                {
                    Address = user.Email, Name = user.Username
                }, "PasswordLost", new
                {
                    username          = user.Username,
                    resetpasswordlink = $"{new Uri(this.appSettings.Environment.FrontUrl, $"#/user/resetpassword/{token}")}",
                    sitename          = this.appSettings.Environment.Name,
                    siteurl           = this.appSettings.Environment.FrontUrl.ToString(),
                    unsubscribeurl    = new Uri(this.appSettings.Environment.FrontUrl, "/user/unsubscribe").ToString(),
                });
            }
            catch (Exception ex)
            {
                // TODO: Gérer les exceptions, avec message localisé
                this.logger.LogError(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenFailed"].Value));
                return(this.Problem(
                           statusCode: (int)HttpStatusCode.InternalServerError,
                           title: ex.ToString(),
                           detail: ex.StackTrace));
            }

            this.logger.LogDebug(string.Format(CultureInfo.InvariantCulture, this.localizer["LogPasswordLostTokenSuccess"].Value, new { value = model.Email ?? model.Username }));
            return(this.Ok());
        }