Exemplo n.º 1
0
    public async Task<IHttpActionResult> UpdateUser(UserProfileViewModel userProfileViewModel)
    {
      if (ModelState.IsValid)
      {
        UserProfile user = await UserManager.FindByIdAsync(userProfileViewModel.Id);

        if (user == null)
        {
          return BadRequest();
        }

        if (user.Roles.Any())
        {
          IdentityUserRole role = user.Roles.FirstOrDefault();

          if ((!userProfileViewModel.RoleId.IsEmpty() && role != null && !role.RoleId.Equals(userProfileViewModel.RoleId)))
          {
            IdentityResult removeFromRoleResult = UserManager.RemoveFromRole(user.Id,
              RoleManager.FindById(role.RoleId).
                Name);

            IHttpActionResult removeFromRoleErrorResult = GetErrorResult(removeFromRoleResult);

            if (removeFromRoleErrorResult != null)
            {
              return removeFromRoleErrorResult;
            }
            IdentityResult addToRoleResult = await UserManager.AddToRoleAsync(user.Id,
              RoleManager.FindById(userProfileViewModel.RoleId).
                Name);

            IHttpActionResult addToRoleErrorResult = GetErrorResult(addToRoleResult);

            if (addToRoleErrorResult != null)
            {
              return addToRoleErrorResult;
            }
          }
          else if (userProfileViewModel.RoleId.IsEmpty())
          {
            IdentityResult removeFromRoleResult = UserManager.RemoveFromRole(user.Id,
              RoleManager.FindById(role.RoleId).
                Name);

            IHttpActionResult removeFromRoleErrorResult = GetErrorResult(removeFromRoleResult);

            if (removeFromRoleErrorResult != null)
            {
              return removeFromRoleErrorResult;
            }
          }
        }
        else if (!userProfileViewModel.RoleId.IsEmpty())
        {
          IdentityResult addToRoleResult = await UserManager.AddToRoleAsync(user.Id,
            RoleManager.FindById(userProfileViewModel.RoleId).
              Name);

          IHttpActionResult addToRoleErrorResult = GetErrorResult(addToRoleResult);

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

        if (!user.Activated && userProfileViewModel.Activated)
        {
          string authority = HttpContext.Current.Request.Url.Authority;

          var url = string.Format("http://{0}/account/login",
            authority);

          var notification = new AccountNotificationModel{
                                                           DisplayName = user.UserName,
                                                           Url = url
                                                         };

          string body = ViewRenderer.RenderView("~/Views/Mailer/accountActivated.cshtml",
            notification);

          await UserManager.SendEmailAsync(user.Id,
            "EnergieNetz: Ihr Konto wurde freigeschaltet",
            body);
        }

        user.Update(userProfileViewModel);

        IdentityResult updateUserResult = await UserManager.UpdateAsync(user);

        if (updateUserResult.Succeeded)
        {
          //var logger = UserManager.AuditLogger;
          //var log = logger.LastLog;
          //log.Username = UserManager.FindById(User.Identity.GetUserId()).UserName;
          //log.ToXml(XmlWriter.Create("../../temp/auditLog.xml"));

          return Ok();
        }

        IHttpActionResult updateUserErrorResult = GetErrorResult(updateUserResult);
        return updateUserErrorResult;
      }
      string errors = ModelState.Values.SelectMany(modelState => modelState.Errors).
        Aggregate(string.Empty,
          (current, error) => current + (error.ErrorMessage + Environment.NewLine));
      throw new Exception(errors);
    }
Exemplo n.º 2
0
    public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordBindingModel model)
    {
      if (ModelState.IsValid)
      {
        UserProfile user = await UserManager.FindByEmailAsync(model.Email);
        if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
        {
          ModelState.AddModelError("",
            "Entweder existiert der Benutzer nicht oder das Konto wurde noch nicht aktiviert.");
          return BadRequest(ModelState);
        }

        string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
        string callbackUrl = Url.Content("~/account/resetpassword?email=") + HttpUtility.UrlEncode(model.Email) + "&code=" + HttpUtility.UrlEncode(code);

        var notification = new AccountNotificationModel{
                                                         Url = callbackUrl,
                                                         DisplayName = user.UserName
                                                       };



        string body = ViewRenderer.RenderView("~/Views/Mailer/PasswordReset.cshtml",
          notification);
        await UserManager.SendEmailAsync(user.Id,
          "EnergieNetz: Kennwort zurücksetzen",
          body);

        return Ok();
      }

      // If we got this far, something failed
      return BadRequest(ModelState);
    }
Exemplo n.º 3
0
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
      if (!ModelState.IsValid)
      {
        return BadRequest(ModelState);
      }

      var user = new UserProfile
      {
        UserName = model.UserName,
        FirstName = model.FirstName,
        LastName = model.LastName,
        PhoneNumber = model.PhoneNumber,
        Email = model.Email,
        EmailConfirmed = false,
      };

      if (model.NetworkId != null)
      {
        Guid networkId = Guid.Parse(model.NetworkId);
        Network network = _unitOfWork.NetworkRepository.First(n => n.NetworkId == networkId, "NetworkCompanies");
        NetworkCompany nc = CreateCompany(model, network);
        network.NetworkCompanies.Add(nc);
        user.CompanyId = nc.Company.CompanyId;
      }
      else if (model.CompanyId != null)
      {
        user.CompanyId = Guid.Parse(model.CompanyId);
      }

      _unitOfWork.Commit();

      IdentityResult identityResult = await UserManager.CreateAsync(user,
        model.Password);
      
      if (identityResult.Succeeded && (model.NetworkId != null || model.CompanyId != null))
      {
        UserManager.AddToRole(user.Id,
          "User");
      }

      IHttpActionResult createResult = GetErrorResult(identityResult);

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

      UserProfile justCreatedUser = await UserManager.FindByNameAsync(model.UserName);

      string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

      string callbackUrl = Url.Link("ConfirmEmail",
        new{
             userId = user.Id,
             code
           });

      var notification = new AccountNotificationModel{
                                                       Code = code,
                                                       Url = callbackUrl,
                                                       UserId = justCreatedUser.Id,
                                                       Email = justCreatedUser.Email,
                                                       DisplayName = justCreatedUser.UserName
                                                     };

      string body = ViewRenderer.RenderView("~/Views/Mailer/NewAccount.cshtml",
        notification);

      await UserManager.SendEmailAsync(user.Id,
        "EnergieNetz: Konto aktivieren",
        body);

      DeleteInvitation(model);

      return Ok();
    }
Exemplo n.º 4
0
    public async Task<IHttpActionResult> ResendConfirmationEmail()
    {
      UserProfile user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
      string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
      string callbackUrl = Url.Link("ConfirmEmail",
        new{
             userId = user.Id,
             code
           });

      var notification = new AccountNotificationModel{
                                                       Code = code,
                                                       Url = callbackUrl,
                                                       UserId = user.Id,
                                                       Email = user.Email,
                                                       DisplayName = user.UserName
                                                     };

      string body = ViewRenderer.RenderView("~/Views/Mailer/NewAccount.cshtml",
        notification);

      var msg = new IdentityMessage{
                                     Destination = notification.Email,
                                     Body = body,
                                     Subject = "EnergieNetz: Konto aktivieren"
                                   };

      await UserManager.EmailService.SendAsync(msg);

      //var bodyBuilder = new StringBuilder();
      //bodyBuilder.AppendFormat("Hallo {0}",
      //  user.UserName).
      //  AppendLine();
      //bodyBuilder.AppendFormat("Das Konto wurde erfolgreich erstellt. Nur noch ein Schritt").
      //  AppendLine();
      //bodyBuilder.AppendFormat("Klicken Sie auf den folgenden Link, um die Anmeldung zu bestätigen.").
      //  AppendLine();
      //bodyBuilder.AppendFormat("{0}",
      //  callbackUrl).
      //  AppendLine();


      //body = bodyBuilder.ToString();

      //await UserManager.SendEmailAsync(user.Id,
      //  "EnergieNetz: Konto aktivieren",
      //  body);

      return Ok();
    }