Exemplo n.º 1
0
        public async Task <IActionResult> RegisterClient([FromBody] RegisterClientViewModel Credentials)
        {
            if (ModelState.IsValid)
            {
                var client = new ClientUser {
                    UserName    = Credentials.Email,
                    Email       = Credentials.Email,
                    FirstName   = Credentials.FirstName,
                    LastName    = Credentials.LastName,
                    Gender      = Credentials.Gender,
                    BirthDay    = Credentials.BirthDay,
                    StreetName  = Credentials.StreetName,
                    HouseNumber = Credentials.HouseNumber,
                    Province    = Credentials.Province,
                    District    = Credentials.District,
                };
                var result = await _userManager.CreateAsync(client, Credentials.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(client, "client");

                    await _signInManager.SignInAsync(client, isPersistent : false);

                    return(Ok("User successfully registered"));
                }
                return(Errors(result));
            }
            return(Error("Unexpected error"));
        }
Exemplo n.º 2
0
        public async Task <ActionResult> Register(RegisterClientViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserDTO        user = _mapper.Map <RegisterClientViewModel, UserDTO>(model);
                IdentityResult result;
                try
                {
                    result = await _userManager.CreateAsync(user, user.Password);
                }
                catch (ArgumentNullException exception)
                {
                    return(Content(exception.Message));
                }

                if (result.Succeeded)
                {
                    var currentUser = await _userManager.FindByNameAsync(model.UserName);

                    var addToRoleResult = await _userManager.AddToRoleAsync(currentUser.Id, "User");

                    if (addToRoleResult.Succeeded)
                    {
                        return(View("SuccessRegistration"));
                    }
                    ModelState.AddModelError("", @"Неудачная попытка регистрации.");
                    return(View(model));
                }
            }

            return(View(model));
        }
Exemplo n.º 3
0
        public ActionResult DeleteConfirmed(int id)
        {
            RegisterClientViewModel registerClientViewModel = db.RegisterClientViewModels.Find(id);

            db.RegisterClientViewModels.Remove(registerClientViewModel);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
        public IActionResult Register(RegisterClientViewModel newClient)
        {
            bool result = clientServices.CreateNewClient(newClient);

            if (!result)
            {
                return(View(newClient));
            }
            else
            {
                return(Redirect("/Client/All/"));
            }
        }
Exemplo n.º 5
0
        // GET: RegisterClient/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            RegisterClientViewModel registerClientViewModel = db.RegisterClientViewModels.Find(id);

            if (registerClientViewModel == null)
            {
                return(HttpNotFound());
            }
            return(View(registerClientViewModel));
        }
Exemplo n.º 6
0
        public async Task <ActionResult> RegisterClient(RegisterClientViewModel model)
        {
            if (ModelState.IsValid)
            {
                CultureInfo cultureinfo = new CultureInfo("nl-NL");
                var         user        = new Client
                {
                    FirstName    = model.FirstName,
                    LastName     = model.LastName,
                    DOB          = DateTime.Parse(model.DOB.ToString(), cultureinfo),
                    Sex          = model.Sex,
                    UserName     = model.UserName,
                    Email        = model.Email,
                    Height       = model.Height,
                    Weight       = model.Weight,
                    TargetWeight = model.TargetWeight,
                    LifeStyle    = model.LifeStyle,
                    FitnessPlan  = model.FitnessPlan
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    UserManager.AddToRole(user.Id, "Client");

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

                    var callbackUrl = Url.Action(
                        "ConfirmEmail", "Account",
                        new { userId = user.Id, code = code },
                        protocol: Request.Url.Scheme);
                    EmailSender es = new EmailSender();
                    es.Send(user.Email,
                            "Confirm your account",
                            "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");


                    ModelState.Clear();

                    return(View("ConfirmEmail"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 7
0
        public ActionResult Create(RegisterClientViewModel model)
        {
            if (ModelState.IsValid)
            {
                string userid = User.Identity.GetUserId();
                var    user   = new Client {
                    clientId = userid, clientName = model.clientName, phone = model.phone
                };
                db.Clients.Add(user);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            var client = db.Clients.ToList();

            return(View(client));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Register(RegisterClientViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new Client {
                    UserName = model.UserName, Email = model.Email, AvatarID = model.AvatarID
                };

                /*
                 *      If email don't need to be confirmed, use this line instead of the above:
                 *      var user = new Client { UserName = model.UserName, Email = model.Email, AvatarID = model.AvatarID, EmailConfirmed = true };
                 */
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    /*
                     *      If email confirmation not needed, use this line only instead of the below:
                     *      await _signInManager.SignInAsync(user, isPersistent: false);
                     */
                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

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

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

                    // My edit:
                    TempData["Status"] = "Thank you for you registration." + Environment.NewLine + "You need to confirm your email address before you can login and use the restricted areas on the site." + Environment.NewLine + "A confirmation link has been sent to your email.";
                    TempData["Color"]  = "success";
                    return(RedirectToAction(nameof(Login)));
                    // My edit end, next line commented out.
                    //return RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Exemplo n.º 9
0
        public bool CreateNewClient(RegisterClientViewModel modelClient)
        {
            Client newClient = new Client
            {
                FirstName   = modelClient.FirstName,
                LastName    = modelClient.LastName,
                PhoneNumber = modelClient.PhoneNumber,
                Email       = modelClient.Email,
                IsAdult     = modelClient.IsAdult
            };

            this.context.Clients.Add(newClient);
            this.context.SaveChanges();
            newClient = GetClient(newClient.Id);
            if (newClient is null)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 10
0
        public async Task <ActionResult> Register(RegisterClientViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Name, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(dbAsp));

                if (result.Succeeded)
                {
                    if (!userManager.IsInRole(user.Id, "cliente"))
                    {
                        userManager.AddToRole(
                            user.Id,
                            "cliente"
                            );
                    }

                    var cliente = new Cliente
                    {
                        ClienteNombre   = model.DName,
                        UsuarioEmail    = model.Email,
                        ClienteTelefono = model.Phone,
                        ClienteSexo     = model.Gender.ToString(),
                        ClienteFchNaci  = model.BirthDate
                    };

                    db.Clientes.Add(cliente);
                    db.SaveChanges();

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }
            return(View(model));
        }
Exemplo n.º 11
0
        /// <summary>
        /// This email sent when client register by himself
        /// </summary>
        /// <param name="emailService"></param>
        /// <param name="email"></param>
        /// <param name="link"></param>
        /// <param name="domainName"></param>
        /// <param name="model"></param>
        public static void SendEmailConfirmationClientAsync(this IEmailService emailService, string email, string link, string domainName, RegisterClientViewModel model)
        {
            //Email sending code
            EmailAddress toEmailAddress = new EmailAddress();

            toEmailAddress.Name    = email;
            toEmailAddress.Address = email;
            var companyName = model.CompanyName;
            var loginUrl    = domainName + "/Account/LoginClient";

            EmailMessage emailMessage = new EmailMessage()
            {
                ToAddresses = new List <EmailAddress>()
                {
                    toEmailAddress
                },
                Subject = "メールアドレス認証のお願い",
                Content = $"{companyName},<br/><br/>オールジョブスジャパン、企業アカウントへの登録ありがとうございます。本登録はまだ完了しておりません。次のURLをクリックし、メールアドレスを認証し、本登録を完了して下さい。<br/><br/><a href = '{HtmlEncoder.Default.Encode(link)}'> {HtmlEncoder.Default.Encode(link)} </a><br/><br/> 完了後、企業ログインページよりログインが可能になります。<br/> ログイン URL<br/> <br/><a href = 'http://www.{HtmlEncoder.Default.Encode(loginUrl)}' > http://www.{HtmlEncoder.Default.Encode(loginUrl)}</a><br/><br/>ログイン後、人材の募集条件をご入力下さい。<br/><br/>今後貴社の人材募集に携われることを楽しみにしております<br/><br/><table><tr><td colspan = '2'></tr><tr><td> 企業名 : </td><td> {model.CompanyName} </td></tr><tr><td> 企業URL :</td><td> {model.WebsiteUrl}</td></tr><tr><td> 担当者名 :</td><td> {model.ContactPerson} </td></tr><tr><td> 連絡用Email / ユーザー名 :</td><td> {model.CompanyEmail} </td></tr></table><br/><br/><br/>株式会社オールジョブスジャパン<br/>All Jobs Japan<br/>URL : <a href = 'http://www.jobsjapan.net'>http://www.jobsjapan.net</a><br/>"
            };

            emailService.Send(emailMessage);
            //End email code
        }
Exemplo n.º 12
0
        public async Task <ActionResult> Register(RegisterClientViewModel model) // J'ai changé le viewModel pour y mettre le mien
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

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

                    // creer mon utilisateur ici

                    IRepository <Client>  repClient = new EFRepository <Client>();
                    IRepository <Adresse> repAdr    = new EFRepository <Adresse>();
                    Adresse adrFact = new Adresse()
                    {
                        numero       = model.AdresseFacturation.numero
                        , voie       = model.AdresseFacturation.voie
                        , codePostal = model.AdresseFacturation.codePostal
                        , ville      = model.AdresseFacturation.ville
                        , pays       = model.AdresseFacturation.pays
                    };
                    repAdr.Creer(adrFact);

                    //int themeValue = 0;
                    //int.TryParse(model.theme.Value,out themeValue);
                    //{
                    //string idC = user.Id;

                    Client niouClient = new Client()
                    {
                        id       = user.Id
                        , actif  = true
                        , nom    = model.client.nom
                        , prenom = model.client.prenom
                        , tel    = model.client.tel
                        , theme  = model.client.theme
                        , idAdresseFacturation = repAdr.Lister().Where(a => (a.numero == adrFact.numero &&
                                                                             a.voie == adrFact.voie && a.ville == adrFact.ville && a.codePostal == adrFact.codePostal &&
                                                                             a.pays == adrFact.pays)).First().id
                    };

                    repClient.Creer(niouClient);

                    // Pour plus d'informations sur l'activation de la confirmation de compte et de la réinitialisation de mot de passe, visitez https://go.microsoft.com/fwlink/?LinkID=320771
                    // Envoyer un message électronique avec ce lien
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirmez votre compte", "Confirmez votre compte en cliquant <a href=\"" + callbackUrl + "\">ici</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
                ViewBag.Erreurs = result.Errors.ToString();
            }

            // Si nous sommes arrivés là, un échec s’est produit. Réafficher le formulaire
            ViewBag.listeThemes = OutilsTirelire.themes;


            return(View());
        }
Exemplo n.º 13
0
        public async Task <ActionResult> RegisterAsClient(RegisterClientViewModel model)
        {
            if (ModelState.IsValid)
            {
                string username = ConfigurationManager.AppSettings["CompanyCheckAPIKey"];
                string password = "";
                var    encoded  = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}", username, password)));

                JToken token = null;

                using (var client = new HttpClient())
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", encoded);

                    string address = "https://api.companieshouse.gov.uk";
                    string comName = "/search/companies?q=" + model.CompanyName;

                    string newUri = address + comName;
                    Uri    uri    = new Uri(newUri);

                    HttpResponseMessage response = await client.GetAsync(uri);

                    if (response.IsSuccessStatusCode)
                    {
                        string textResult = await response.Content.ReadAsStringAsync();

                        token = JObject.Parse(textResult);
                    }
                    else
                    {
                        return(View(model));
                    }
                }

                var    companyNumbers = token.SelectTokens("items[*].company_number");
                string companyNumber  = "";

                foreach (string cn in companyNumbers)
                {
                    if (model.CompanyRegNum == cn)
                    {
                        companyNumber = cn;
                    }
                }

                if (companyNumber != model.CompanyRegNum)
                {
                    return(View(model));
                }
                else
                {
                    var user = new ApplicationUser {
                        UserName = model.Email, Email = model.Email
                    };
                    user.CompanyName   = model.CompanyName;
                    user.CompanyRegNum = model.CompanyRegNum;

                    var result = await UserManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        // Comment the following line to prevent log in until the user is confirmed.

                        UserManager.AddToRole(user.Id, "Client");
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        //string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");

                        // Uncomment to debug locally
                        // TempData["ViewBagLink"] = callbackUrl;

                        ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                                          + "before you can log in.";

                        //return View("Info");
                        return(RedirectToAction("Index", "Home"));
                    }
                    AddErrors(result);
                }
            }

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