Exemplo n.º 1
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); // входим через сторонние ресурсы
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = Input.Email, Email = Input.Email, Name = Input.Name, PhoneNumber = Input.PhoneNumber
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    // Проверяем, существует ли роль => создаем
                    if (!await _roleManager.RoleExistsAsync(SD.AdminEndUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.AdminEndUser));
                    }

                    if (!await _roleManager.RoleExistsAsync(SD.SuperAdminEndUser))
                    {
                        await _roleManager.CreateAsync(new IdentityRole(SD.SuperAdminEndUser));
                    }

                    // Приверяем, стоит ли галочка в чекбоксе
                    if (Input.IsSuperAdmin)
                    {
                        await _userManager.AddToRoleAsync(user, SD.SuperAdminEndUser);
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, SD.AdminEndUser);
                    }


                    _logger
                    .LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "AdminUsers", new { area = "Admin" }));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 2
0
        public async Task <IActionResult> OnPostAsync()
        {
            var userid = Guid.NewGuid().ToString();

            if (ModelState.IsValid)
            {
                // var userid = Guid.NewGuid().ToString();
                var user = new JobProfile
                {
                    Id           = userid,
                    FullName     = Input.FullName,
                    Role         = Roles.Applicant,
                    Organisation = Input.Organisation,
                    UserName     = Input.Email,
                    Email        = Input.Email,
                    Resume       = new JobResume
                    {
                        Id     = Guid.NewGuid().ToString(),
                        UserId = userid
                    }
                };

                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var roleExists = await _roleManager.RoleExistsAsync("Applicant");

                    if (!roleExists)
                    {
                        await _roleManager.CreateAsync(new IdentityRole("Applicant"));
                    }

                    await _userManager.AddToRoleAsync(user, "Applicant");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = user.Id, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email,
                                                          "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : true);

                        return(LocalRedirect(Url.Content("~/")));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(Page());
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            var company = await this.companyRepository.AllAsNoTracking().FirstOrDefaultAsync(c => c.Name == this.Input.Company);

            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName            = this.Input.Email,
                    Email               = this.Input.Email,
                    FirstName           = this.Input.FirstName,
                    LastName            = this.Input.LastName,
                    CompanyId           = company.Id,
                    Education           = this.Input.Education,
                    Age                 = this.Input.Age,
                    FacebookAccountLink = this.Input.FacebookAccountLink,
                    ImageUrl            = this.Input.ImageUrl,
                    TwitterAccountLink  = this.Input.TwitterAccountLink,
                    LinkedInAccountLink = this.Input.LinkedInAccountLink,
                    Points              = 100,
                };

                var result = await _userManager.CreateAsync(user, this.Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 4
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new User {
                    UserName = StringHelper.GetUntilOrEmpty(Input.Email, "@"), Email = Input.Email, FirstName = Input.FirstName, LastName = Input.LastName, PictureName = Input.PictureName, Role = ((Roles)(Input.IsEmployer ? 3 : 0)), isExternal = true
                };

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);


                        if (Input.Email != Input.EmailFromSocial)
                        {
                            await _senderService.SendEmailAsync(Input.Email,
                                                                "Потвърди емайл адрес",
                                                                $"<a href='{HtmlEncoder.Default.Encode(callbackUrl)}'> <img src='https://i.imgur.com/MOYSeFJ.jpg'> </a> <br>Изпратено с <3 от GrandJob.eu <br>София, Младост 4.");
                        }
                        else
                        {
                            user.profileConfirmed = true;
                            user.EmailConfirmed   = true;

                            await _userManager.UpdateAsync(user);
                        }


                        if (_userManager.Users.Count() == 1)
                        {
                            await CreateRole();

                            await _userManager.AddToRoleAsync(user, "Admin");

                            await _userManager.RemoveFromRoleAsync(user, "User");

                            user.profileConfirmed = true;
                            user.EmailConfirmed   = true;
                            user.Role             = Roles.Admin;
                        }
                        else
                        {
                            if (Input.IsEmployer)
                            {
                                await _userManager.AddToRoleAsync(user, "Employer");

                                //user.Role = Roles.Employer;
                            }
                            else
                            {
                                await _userManager.AddToRoleAsync(user, "User");

                                //user.Role = Roles.User;
                            }
                        }

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _userManager.UpdateAsync(user);

                        await _signInManager.RefreshSignInAsync(user);

                        await _signInManager.SignInAsync(user, isPersistent : false, info.LoginProvider);


                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ProviderDisplayName = info.ProviderDisplayName;
            ReturnUrl           = returnUrl;
            return(Page());
        }
Exemplo n.º 5
0
        private string GetIDTokenFromServiceAccount(ServiceAccountCredential svc_credential, string target_audience)
        {
            TimeSpan unix_time = (System.DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));

            long    now    = (long)unix_time.TotalSeconds;
            long    exp    = now + 3600;
            JObject header = new JObject
            {
                ["alg"]  = "RS256",
                ["type"] = "JWT"
            };

            JObject claim = new JObject {
                ["iss"]             = svc_credential.Id,
                ["aud"]             = "https://oauth2.googleapis.com/token",
                ["exp"]             = exp,
                ["iat"]             = now,
                ["target_audience"] = target_audience
            };

            System.Text.UTF8Encoding e  = new System.Text.UTF8Encoding();
            String jwt_header_and_claim = WebEncoders.Base64UrlEncode(e.GetBytes(header.ToString())) + "." + WebEncoders.Base64UrlEncode(e.GetBytes(claim.ToString()));

            var jwt_signature = svc_credential.CreateSignature(System.Text.Encoding.UTF8.GetBytes(jwt_header_and_claim));

            WebClient           client   = new WebClient();
            NameValueCollection formData = new NameValueCollection();

            formData["grant_type"]         = "urn:ietf:params:oauth:grant-type:jwt-bearer";
            formData["assertion"]          = jwt_header_and_claim + "." + jwt_signature;;
            client.Headers["Content-type"] = "application/x-www-form-urlencoded";
            try
            {
                byte[] responseBytes = client.UploadValues("https://oauth2.googleapis.com/token", "POST", formData);
                string Result        = Encoding.UTF8.GetString(responseBytes);

                var assertion_response = JObject.Parse(Result);
                var id_token           = assertion_response["id_token"];

                return(id_token.ToString());
            } catch (WebException ex)
            {
                Stream       receiveStream = ex.Response.GetResponseStream();
                Encoding     encode        = System.Text.Encoding.GetEncoding("utf-8");
                StreamReader readStream    = new StreamReader(receiveStream, encode);
                string       pageContent   = readStream.ReadToEnd();
                Console.WriteLine("Error: " + pageContent);
                throw new System.Exception("Error while getting IDToken " + ex.Message);
            }
        }
Exemplo n.º 6
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName      = Input.Email,
                    Email         = Input.Email,
                    StreetAddress = Input.StreetAddress,
                    City          = Input.City,
                    State         = Input.State,
                    PostalCode    = Input.PostalCode,
                    Name          = Input.Name,
                    PhoneNumber   = Input.PhoneNumber,
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, SD.Role_Customer);

                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }
Exemplo n.º 7
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            _roleManager.CreateAsync(new IdentityRole(SD.MentorRole)).GetAwaiter().GetResult();
            _roleManager.CreateAsync(new IdentityRole(SD.InternRole)).GetAwaiter().GetResult();

            //retrieve the role from the form
            string role = Request.Form["rdUserRole"].ToString();

            /*if (role == "")
             * { role = SD.AdministratorRole; }*/       //make the first login a manager)
            returnUrl = returnUrl ?? Url.Content("~/"); //null-coalescing assignment operator ??= assigns the value of right-hand operand to its left-hand operand only if the left-hand is nulll
            if (ModelState.IsValid)
            {
                //expand identityuser with applicationuser properties
                var user = new ApplicationUser
                {
                    UserName    = Input.Email,
                    Email       = Input.Email,
                    FirstName   = Input.FirstName,
                    LastName    = Input.LastName,
                    PhoneNumber = Input.PhoneNumber
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                //add the roles to the ASPNET Roles table if they do not exist yet
                if (!await _roleManager.RoleExistsAsync(SD.AdministratorRole))
                {
                    _roleManager.CreateAsync(new IdentityRole(SD.AdministratorRole)).GetAwaiter().GetResult();
                    _roleManager.CreateAsync(new IdentityRole(SD.ApplicantRole)).GetAwaiter().GetResult();
                    _roleManager.CreateAsync(new IdentityRole(SD.JudgeRole)).GetAwaiter().GetResult();
                    _roleManager.CreateAsync(new IdentityRole(SD.MentorRole)).GetAwaiter().GetResult();
                    _roleManager.CreateAsync(new IdentityRole(SD.InternRole)).GetAwaiter().GetResult();
                }
                if (result.Succeeded)
                //assign role to the user (from the form radio options available after the first manager is created)
                {
                    switch (role)
                    {
                    case SD.AdministratorRole:
                        await _userManager.AddToRoleAsync(user, SD.AdministratorRole);

                        break;

                    case SD.ManagementRole:
                        await _userManager.AddToRoleAsync(user, SD.ManagementRole);

                        break;

                    case SD.MentorRole:
                        await _userManager.AddToRoleAsync(user, SD.MentorRole);

                        break;

                    case SD.JudgeRole:
                        await _userManager.AddToRoleAsync(user, SD.JudgeRole);

                        break;

                    default:
                        await _userManager.AddToRoleAsync(user, SD.ApplicantRole);

                        break;
                    }

                    _logger.LogInformation("User created a new account with password.");
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);
                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }
            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 8
0
        /// <summary>
        /// este método reage a uma interação por HTTP POST
        /// </summary>
        /// <param name="fotoUser">Fotografia do novo Utilizador</param>
        /// <param name="returnUrl">caso exista, define para onde se reencaminha a ação do programa, após o Registo </param>
        /// <returns></returns>
        public async Task <IActionResult> OnPostAsync(IFormFile fotoUser, string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            //   ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();


            if (ModelState.IsValid)
            {
                // se o InputModel é válido...

                // neste sítio, temos de adicionar o código
                // construído na criação de um novo veterinário
                // para a adição de uma fotografia
                // **************************************
                // processar a fotografia
                // **************************************
                // vars. auxiliares
                string caminhoCompleto = "";
                string nomeFoto        = "";
                bool   haImagem        = false;

                // será q há fotografia?
                //    - uma hipótese possível, seria reenviar os dados para a View e solicitar a adição da imagem
                //    - outra hipótese, será associar ao veterinário uma fotografia 'por defeito'
                if (fotoUser == null)
                {
                    nomeFoto = "noVet.png";
                }
                else
                {
                    // há ficheiro
                    // será o ficheiro uma imagem?
                    if (fotoUser.ContentType == "image/jpeg" ||
                        fotoUser.ContentType == "image/png")
                    {
                        // o ficheiro é uma imagem válida
                        // preparar a imagem para ser guardada no disco rígido
                        // e o seu nome associado ao Veterinario
                        Guid g;
                        g = Guid.NewGuid();
                        string extensao = Path.GetExtension(fotoUser.FileName).ToLower();
                        string nome     = g.ToString() + extensao;
                        // onde guardar o ficheiro
                        caminhoCompleto = Path.Combine(_caminho.WebRootPath, "Imagens\\Users", nome);
                        // associar o nome do ficheiro ao Veterinário
                        nomeFoto = nome;
                        // assinalar que existe imagem e é preciso guardá-la no disco rígido
                        haImagem = true;
                    }
                    else
                    {
                        // há imagem, mas não é do tipo correto
                        nomeFoto = "noVet.png";
                    }
                }

                // criação de um novo utilizador
                var user = new ApplicationUser {
                    UserName   = Input.Email,
                    Email      = Input.Email,
                    Nome       = Input.Nome,
                    Fotografia = nomeFoto,
                    Timestamp  = DateTime.Now
                };

                // vou escrever esses dados na BD
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    // se cheguei aqui, é pq houve sucesso na escrita na BD

                    // vou, agora, guardar a imagem no disco rígido do Servidor
                    // se há imagem, vou guardá-la no disco rígido
                    if (haImagem)
                    {
                        using var stream = new FileStream(caminhoCompleto, FileMode.Create);
                        await fotoUser.CopyToAsync(stream);
                    }



                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 9
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                int checkYearInt;
                try
                {
                    // verifica se o ano está correto
                    checkYearInt = Int32.Parse(Input.Year);
                }
                catch (Exception)
                {
                    // caso nao recarrega a pagina
                    return(Page());
                }
                // cria o objeto utilizador
                var newutilizador = new Utilizador
                {
                    username = Input.Name,
                    email    = Input.Email
                };
                // cria o objeto carro
                var newcar = new Car
                {
                    LicensePlate = Input.LicensePlate,
                    Color        = Input.Color,
                    Manufacturer = Input.Manufacturer,
                    Model        = Input.Model,
                    Year         = Int32.Parse(Input.Year),
                    utilizador   = newutilizador,
                    username     = Input.Name
                };
                // cria o utilizador do tipo IdentityUser
                var user = new IdentityUser {
                    UserName = Input.Name, Email = Input.Email
                };
                // é guardado no objeto resultado se o utilizador foi criado com sucesso
                try
                {
                    var result_uti = await _context.AddAsync(newutilizador);

                    var result_car = await _context.AddAsync(newcar);

                    var finalresult = await _context.SaveChangesAsync();
                }
                catch (Exception)
                {
                    return(Page());
                }

                var result = await _userManager.CreateAsync(user, Input.Password);

                // Caso seja sucedido
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code, returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");



                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 10
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                ApplicationUser user;
                IdentityResult  createUser;
                IdentityResult  addRole;

                if (Input.AccountType == AccountType.Host)
                {
                    user = new Host {
                        UserName = Input.Email, Email = Input.Email, CreatedOn = DateTime.UtcNow
                    };
                    createUser = await _userManager.CreateAsync(user, Input.Password);

                    addRole = await _userManager.AddToRoleAsync(user, AccountType.Host);
                }
                else
                {
                    user = new Data.Models.Client {
                        UserName = Input.Email, Email = Input.Email, CreatedOn = DateTime.UtcNow
                    };
                    createUser = await _userManager.CreateAsync(user, Input.Password);

                    addRole = await _userManager.AddToRoleAsync(user, AccountType.Client);
                }

                if (createUser.Succeeded && addRole.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password, account type, and role.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }

                foreach (var error in createUser.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }

                foreach (var error in addRole.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 11
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                // var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };

                // override default user model to our ApplicationUser
                var user = new ApplicationUser
                {
                    UserName  = Input.Email,
                    Email     = Input.Email,
                    FirstName = Input.FirstName,
                    LastName  = Input.LastName,
                    ImageUrl  = "img_seed/default-user.jpg",
                    Role      = Input.Role
                };

                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    if (user.Role == null)
                    {
                        await _userManager.AddToRoleAsync(user, SD.Role_User);
                    }

                    // send Email after valid register
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");


                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else if (user.Role == null)
                    {
                        // register from site
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                    else
                    {
                        // Admin register with choosing roles from admin panel
                        return(RedirectToAction("Index", "User", new { Area = "Admin" }));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 12
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            using (var context = new ClientDbContext())
            {
                var _usedEmail = await context.AspNetUsers.Where(x => x.Email == Input.Email).ToListAsync();

                var _usedUername = await context.AspNetUsers.Where(x => x.UserName == Input.Username).ToListAsync();

                if (_usedEmail.Count == 0 && _usedUername.Count == 0)
                {
                    if (ModelState.IsValid)
                    {
                        var user = new AppUser
                        {
                            HoTen       = Input.HoTen,
                            UserName    = Input.Username,
                            Email       = Input.Email,
                            NgaySinh    = Input.NgaySinh,
                            CMND        = Input.CMND,
                            Avatar      = Input.Avatar,
                            PhoneNumber = Input.SDT,
                            GioiTinh    = Input.GioiTinh,
                            DiaChi      = Input.DiaChi + ","
                                          + context.Ward.Find(Input.XaPhuong).Name + ","
                                          + context.District.Find(Input.QuanHuyen).Name
                                          + "," + context.Province.Find(Input.TinhThanh).Name
                        };

                        string content = System.IO.File.ReadAllText("RegisterEmail.html");
                        content = content.Replace("{{Hoten}}", user.HoTen);
                        content = content.Replace("{{username}}", user.UserName);
                        content = content.Replace("{{phone}}", user.PhoneNumber);
                        content = content.Replace("{{email}}", user.Email);
                        content = content.Replace("{{address}}", user.DiaChi);
                        var result = await _userManager.CreateAsync(user, Input.Password);

                        if (result.Succeeded)
                        {
                            _logger.LogInformation("User created a new account with password.");
                            AspNetUserRoles userrole = new AspNetUserRoles()
                            {
                                RoleId = context.AspNetRoles.FirstOrDefault(x => x.Name == "Khách hàng")?.Id,
                                UserId = user.Id
                            };
                            context.AspNetUserRoles.Add(userrole);
                            context.SaveChanges();
                            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                            code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                            var callbackUrl = Url.Page("/Account/ConfirmEmail", pageHandler: null,
                                                       values: new { area = "Identity", userId = user.Id, code = code },
                                                       protocol: Request.Scheme);

                            content = content.Replace("{{callbackurl}}", $"Vui lòng xác nhận tài khoản bằng cách <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>nhấn vào đây </a>.");

                            await _emailSender.SendEmailAsync(Input.Email, "Email thông tin tài khoản ", $"{System.Net.WebUtility.HtmlDecode(content)}");

                            if (_userManager.Options.SignIn.RequireConfirmedAccount)
                            {
                                return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                            }
                            else
                            {
                                await _signInManager.SignInAsync(user, isPersistent : false);

                                return(LocalRedirect(returnUrl));
                            }
                        }
                        foreach (var error in result.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.Description);
                        }
                    }
                }

                else
                {
                    ModelState.AddModelError(string.Empty, "Username hoặc email đã dùng! ");
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }