//[ValidateAntiForgeryToken]
        public async Task <IActionResult> RegisterCompany([FromBody] RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

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

                    ApplicationUser createdUser = await _userManager.FindByEmailAsync(user.Email);

                    createdUser.Bulstat    = model.Bulstat;
                    createdUser.TownId     = model.TownId;
                    createdUser.IsApproved = false;
                    await _userManager.UpdateAsync(createdUser);

                    await _userManager.AddToRoleAsync(createdUser, "Company");

                    return(Ok());
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> RegisterCompany(RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                bool isBulstatValid = this.ValidateBulstat(model.Bulstat);
                bool isNameValid    = this.ValidateCompanyName(model.CompanyName);

                if (!isBulstatValid)
                {
                    ViewBag.BulstatErrorMessage = "This bulstat is already taken. Bulstat should be unique.";
                }
                else if (!isNameValid)
                {
                    ViewBag.NameErrorMessage = "This company name is already taken. Company name should be unique.";
                }
                else
                {
                    var user = new Company()
                    {
                        UserName = model.Email, Email = model.Email
                    };

                    user.Bulstat     = model.Bulstat;
                    user.CompanyName = model.CompanyName;
                    user.PhoneNumber = model.Phone;
                    user.Address     = model.Address;
                    user.AboutUs     = model.AboutUs;
                    user.WebSite     = model.WebSite;

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

                    if (result.Succeeded)
                    {
                        this.AddBusinessSectors(model.SelectedIds, user.Id);

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

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // 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, "Confirm your account", "Please confirm your account by clicking <a href=\string.Empty + callbackUrl + "\">here</a>");
                        this.TempData["WaitingApproval"] = "Your registration was successfull. You are waiting for approval. Your profile will be active in 24 hours.";
                        return(this.RedirectToAction("RegisterCompany", "Account"));
                    }

                    this.AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            // ViewBag.OriginalSectors = this.data.BusinessSectors.All();
            ViewBag.OriginalSectors = this.Data.BusinessSectors.All()
                                      .Select(s => new SelectListItem {
                Text = s.Name, Value = s.Id.ToString()
            });
            return(this.View(model));
        }
示例#3
0
        public async Task <ActionResult> RegisterCompany(RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Company user = new Company
                    {
                        UserName            = model.Email,
                        Email               = model.Email,
                        CompanyName         = model.CompanyName,
                        HeadOfficeCity      = model.HeadOfficeCity,
                        HeadOfficeContactNo = model.HeadOfficeContactNo,
                        NoOfBranch          = model.NoOfBranch,
                        CompanyMail         = model.Email,
                        CompanyType         = model.CompanyType,

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

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

                        ViewBag.UserType = "Company";
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // 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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                        //user.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole() {RoleId= "0af0aa07-076a-41a9-a53d-d398c5200853",UserId=user.Id});
                        UserManager.AddToRole(user.Id, "Company");
                        db.SaveChanges();
                        return(View("SuccessRegistration"));
                    }
                    AddErrors(result);
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException dbex)
                {
                    Exception raise = dbex;
                    foreach (var validationErrors in dbex.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {
                            string message = string.Format("{0} : {1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage);
                            raise = new InvalidOperationException(message, raise);
                        }
                    }
                    throw raise;
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> RegisterCompany(RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                Internship_Management_SystemEntities db = new Internship_Management_SystemEntities();
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await UserManager.AddToRoleAsync(user.Id, "company");

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

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UshnerManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    RegisterCompanyViewModel newRegisteredCompany = (RegisterCompanyViewModel)model;
                    Company newCompany = new Company();
                    newCompany.CompanyEmail    = newRegisteredCompany.Email;
                    newCompany.CompanyName     = newRegisteredCompany.Name;
                    newCompany.PersonInCharge  = newRegisteredCompany.PersonInCharge;
                    newCompany.ContactNumber   = newRegisteredCompany.ContactNumber;
                    newCompany.CompanyLocation = newRegisteredCompany.CompanyLocation;
                    if (db.Companies.Count() != 0)
                    {
                        var newCompanyOrder = db.Companies.Count() + 1;
                        newCompany.CompanyOrder = newCompanyOrder;
                    }
                    else
                    {
                        newCompany.CompanyOrder = 1;
                    }
                    db.Companies.Add(newCompany);
                    await db.SaveChangesAsync();

                    return(Json(new
                    {
                        redirectUrl = Url.Action("Index", "Home"),
                        isRedirect = true
                    }));
                }
                AddErrors(result);
            }
            return(PartialView("_CompanyRegister", model));
        }
示例#5
0
        public async Task <IActionResult> RegisterCompany()
        {
            if (User.IsAuthenticated())
            {
                return(Redirect($"{HttpContext.GetAppBaseUrl()}/home"));
            }

            var model = new RegisterCompanyViewModel
            {
                CountrySelectListItems = await _organizationService.GetCountrySelectListAsync()
            };

            return(View(model));
        }
        public static CompanyMD Translate(this RegisterCompanyViewModel from, CompanyMD dest = null)
        {
            var to = dest ?? new CompanyMD();

            to.Id          = from.Id;
            to.Name        = from.Name;
            to.IsActive    = true;
            to.Logo        = "";
            to.ImagePath   = "";
            to.CreatedDate = DateTime.Now;
            to.CreatedById = 0;

            return(to);
        }
示例#7
0
        public async Task <ActionResult> RegisterCompany(RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                //var appDbContext = HttpContext.GetOwinContext().Get<EMSDbContext>();
                //using (var context = appDbContext.Database.BeginTransaction())
                //{
                //    try
                //    {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var company = new CompanyMD();
                    company.Name        = model.Name;
                    company.ImagePath   = "";
                    company.Logo        = "";
                    company.CreatedDate = DateTime.Now;
                    company.Id          = user.Id;
                    company.CreatedById = 0;

                    user.Company = company.Translate();
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    var res = _CompanyService.RegisterCompany(company);
                    if (res.HasErrors)
                    {
                        await UserManager.DeleteAsync(user);
                    }
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // 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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                    //    }
                    //    AddErrors(result);
                    //}
                    //catch (Exception)
                    //{
                    //    context.Rollback();
                    //}
                }
            }
            return(View(model));
        }
        public async Task <IActionResult> RegisterCompany(RegisterCompanyViewModel viewModel)
        {
            var    company              = viewModel.Company;
            var    companyImage         = viewModel.Image;
            string companyImageFileName = companyImage.FileName;

            company.Image = companyImageFileName;
            registerLogic.RegisterCompany(company);

            //Add image to root of app
            string mapRoot = "CompanyImages/";

            var companyImagePath = Path.Combine(_hostingEnvironment.WebRootPath, mapRoot);

            await AddFileToDirectory(companyImage, companyImagePath);

            return(RedirectToAction("RegisterCompany"));
        }
示例#9
0
        public ActionResult Register(RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                ViewBag.OrganisationTypeId = new SelectList(this.db.OrganisationType, "OrganisationTypeId", "OrganisationTypeName", model.Company.OrganisationTypeId);

                // Attempt to register the user
                try
                {
                    string retVal  = WebSecurity.CreateUserAndAccount(model.Register.UserName, model.Register.Password);
                    bool   success = WebSecurity.Login(model.Register.UserName, model.Register.Password);

                    //todo check success of user profile create
                    if (model.Register.UserName != null && model.Company != null && success)
                    {
                        if (model.Company.OrganisationTypeId == 0)
                        {
                            model.Company.OrganisationTypeId = 1; // todo temp
                        }

                        int currentUserId = WebSecurity.GetUserId(model.Register.UserName);
                        //// model.Company.UserId = currentUserId;
                        this.db.Company.Add(model.Company);
                        this.db.SaveChanges();

                        model.CompanyUserProfile           = new CompanyUserProfileMap();
                        model.CompanyUserProfile.UserId    = currentUserId;
                        model.CompanyUserProfile.CompanyId = model.Company.CompanyId;
                        this.db.CompanyUserProfileMap.Add(model.CompanyUserProfile);
                        this.db.SaveChanges();
                    }

                    return(this.RedirectToAction("Index", "Home"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError(string.Empty, ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return(this.View(model));
        }
示例#10
0
        public async Task <ActionResult> RegisterComp(RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new CompanyUser {
                    UserName = model.Email, Email = model.Email, LastActivityDate = DateTime.Now
                };
                user.Stiftelse = new Stiftelse
                {
                    Adress        = model.Stiftelse.Adress,
                    Aktnr         = model.Stiftelse.Aktnr,
                    CoAdress      = model.Stiftelse.CoAdress,
                    Förmögenhet   = model.Stiftelse.Förmögenhet,
                    Kommun        = model.Stiftelse.Kommun,
                    Län           = model.Stiftelse.Län,
                    Orgnr         = model.Stiftelse.Orgnr,
                    Postadress    = model.Stiftelse.Postadress,
                    Postnr        = model.Stiftelse.Postnr,
                    Stiftelsenamn = model.Stiftelse.Stiftelsenamn,
                    Stiftelsenr   = model.Stiftelse.Stiftelsenr,
                    Telefon       = model.Stiftelse.Telefon,
                    Ändamål       = model.Stiftelse.Ändamål,
                    År            = model.Stiftelse.År,
                };

                db.SaveChanges();

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

                if (result.Succeeded)
                {
                    await SendConfirmationEmail(user);

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#11
0
        public async Task <ActionResult> RegisterCompany(RegisterCompanyViewModel model)
        {
            if (ModelState.IsValid)
            {
                var company = new Company {
                    Email = model.Email, Name = model.Name
                };
                //context.Companies.Add(company);
                //await context.SaveChangesAsync();
                var user = new CompanyUser {
                    Email = model.Email, Company = company, UserName = model.Email
                };

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

                if (result.Succeeded)
                {
                    inisraRoleManager = new RoleManager <IdentityRole>
                                            (new RoleStore <IdentityRole>(context));
                    var roleResult = UserManager.AddToRole(user.Id, "Company");

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

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // 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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        return(RedirectToAction("Index", "Home"));
                    }
                    AddErrors(roleResult);
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#12
0
        public async Task <IActionResult> RegisterCompany(RegisterCompanyViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;

            if (!await _roleManager.RoleExistsAsync("Company"))
            {
                var role = new IdentityRole("Company");
                await _roleManager.CreateAsync(role);
            }

            if (ModelState.IsValid)
            {
                var user = new Company
                {
                    UserName    = model.Email,
                    Name        = model.Name,
                    Email       = model.Email,
                    About       = model.About,
                    Address     = model.Address,
                    City        = model.City,
                    PhoneNumber = model.PhoneNumber,


                    BussinesType      = model.BussinesType,
                    LogoLink          = model.LogoLink,
                    WebAddress        = model.WebAddress,
                    Established       = model.Established,
                    NumberOfEmployees = model.NumberOfEmployees
                };

                var x = _databaseContext.Individual.FirstOrDefault(g => g.Email == model.Email);
                var y = _databaseContext.Company.FirstOrDefault(g => g.Email == model.Email);
                var z = _databaseContext.Company.FirstOrDefault(g => g.Name.ToLower() == model.Name.ToLower());

                if (z != null)
                {
                    TempData[Constants.Message]       = $"Firma s tim nazivom već postoji\n";
                    TempData[Constants.ErrorOccurred] = true;
                    return(RedirectToAction(nameof(RegisterIndividual), new { retUrl = returnUrl }));
                }

                if (x != null || y != null)
                {
                    TempData[Constants.Message]       = $"Korisnik s tim mailom već postoji.\n";
                    TempData[Constants.ErrorOccurred] = true;
                    return(RedirectToAction(nameof(RegisterIndividual), new { retUrl = returnUrl }));
                }

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

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

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

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

                    //await _signInManager.SignInAsync(user, isPersistent: false);
                    _logger.LogInformation("User created a new account with password.");

                    TempData[Constants.Message]       = $"Uspješno ste se registrirali";
                    TempData[Constants.ErrorOccurred] = false;
                    return(RedirectToAction("Index", "Ad"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
示例#13
0
        public async Task <IActionResult> RegisterCompany(RegisterCompanyViewModel data)
        {
            data.UserName = data.Email;
            //if (data.Email.Contains("@") && data.Email.IndexOf("@", StringComparison.Ordinal) > -1)
            //{
            //    .Substring(0, data.Email.IndexOf("@", StringComparison.Ordinal));
            //}

            if (User.IsAuthenticated())
            {
                return(Redirect($"{HttpContext.GetAppBaseUrl()}/home"));
            }

            if (!ModelState.IsValid)
            {
                data.CountrySelectListItems = await _organizationService.GetCountrySelectListAsync();

                return(View(data));
            }

            var userNameExist = await _userManager.UserManager.FindByNameAsync(data.UserName);

            var userEmailExist = await _userManager.UserManager.FindByEmailAsync(data.Email);

            if (userEmailExist != null)
            {
                data.CountrySelectListItems = await _organizationService.GetCountrySelectListAsync();

                ModelState.AddModelError(string.Empty, "Email address is used!");
                return(View(data));
            }

            if (userNameExist != null)
            {
                data.CountrySelectListItems = await _organizationService.GetCountrySelectListAsync();

                ModelState.AddModelError(string.Empty, "UserName is used!");
                return(View(data));
            }
            var newCompanyOwner = new GearUser
            {
                Email              = data.Email,
                UserName           = data.UserName,
                FirstName          = data.FirstName,
                LastName           = data.LastName,
                AuthenticationType = AuthenticationType.Local,
                EmailConfirmed     = false,
                IsEditable         = true
            };

            //create new user
            var usrReq = await _userManager.UserManager.CreateAsync(newCompanyOwner, data.Password);

            if (!usrReq.Succeeded)
            {
                ModelState.AppendIdentityResult(usrReq);
                data.CountrySelectListItems = await _organizationService.GetCountrySelectListAsync();

                return(View(data));
            }

            var reqTenant = await _organizationService.CreateOrganizationAsync(data);

            if (reqTenant.IsSuccess)
            {
                var claim = new Claim(nameof(Tenant).ToLowerInvariant(), newCompanyOwner.TenantId.ToString());
                newCompanyOwner.TenantId = reqTenant.Result.Id;
                await _userManager.UserManager.UpdateAsync(newCompanyOwner);

                await _userManager.UserManager.AddClaimAsync(newCompanyOwner, claim);

                var generateResult = await _service.GenerateTablesForTenantAsync(reqTenant.Result);

                if (!generateResult.IsSuccess)
                {
                    ModelState.AppendResultModelErrors(generateResult.Errors);
                    return(View(reqTenant.Result.Adapt <RegisterCompanyViewModel>()));
                }

                //Trigger event
                TenantEvents.Company.CompanyRegistered(new CompanyRegisterEventArgs
                {
                    UserName    = newCompanyOwner.UserName,
                    UserId      = newCompanyOwner.Id,
                    CompanyName = reqTenant.Result.Name,
                    UserEmail   = newCompanyOwner.Email
                });

                //send confirm email request
                await _organizationService.SendConfirmEmailRequestAsync(newCompanyOwner);

                var roleReq = await _userManager.AddToRolesAsync(newCompanyOwner, new List <string> {
                    MultiTenantResources.Roles.COMPANY_ADMINISTRATOR
                });

                if (!roleReq.IsSuccess)
                {
                    ModelState.AppendResultModelErrors(roleReq.Errors);
                    return(View(reqTenant.Result.Adapt <RegisterCompanyViewModel>()));
                }

                //sing in new created
                var signResult =
                    await _signInManager.PasswordSignInAsync(data.UserName, data.Password, true, false);

                if (signResult.Succeeded)
                {
                    return(RedirectToAction("Index", "Home"));
                }

                ModelState.AddModelError(string.Empty, "Fail to sign in");

                return(View(reqTenant.Result.Adapt <RegisterCompanyViewModel>()));
            }

            await _userManager.UserManager.DeleteAsync(newCompanyOwner);

            ModelState.AppendResultModelErrors(reqTenant.Errors);

            return(View(reqTenant.Result.Adapt <RegisterCompanyViewModel>()));
        }