public async Task <IHttpActionResult> PostSignup(SignupBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var loginHelper = new LoginHelper(OwinUserManager, OwinAuthenticationManager);

            // Create the user account
            var user = await loginHelper.Signup(model, null, this.GetExtId(), Request.RequestUri);

            var error = loginHelper.InspectErrorAfterSignup(user);

            if (!String.IsNullOrEmpty(error))
            {
                throw new Exception(error);
            }

            // Send the link to the thankyou page. The client code will redirect.
            var url = Url.Link("Default", new { Controller = "Account", Action = "ThankYou", email = model.Email });

            url = url.Replace("https://", "http://"); // Url.Link appears to generate a url using the scheme of the current request.
            return(Ok(url));
            //return StatusCode(HttpStatusCode.Created);
        }
Exemple #2
0
        public IActionResult Signup(SignupBindingModel model,
                                    HttpResponse response)
        {
            var service = new SignupService(Data.Data.Context);

            service.AddUserFromBinding(model);

            this.Redirect(response, "/home/indexlogged");
            return(null);
        }
Exemple #3
0
        public async Task <IServiceResult> SignupAsync(SignupBindingModel signupModel)
        {
            var username   = _randomMaker.NewNumber();
            var duplicated = await FirstAsync(new AccountGetFirstSchema { Username = username });

            while (duplicated != null)
            {
                username   = _randomMaker.NewNumber();
                duplicated = await FirstAsync(new AccountGetFirstSchema { Username = username });
            }

            using (var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) {
                try {
                    var now = DateTime.UtcNow;

                    var account = new AccountAddSchema {
                        Password   = _cryptograph.RNG(signupModel.Password),
                        ProviderId = AccountProvider.Clipboardy.ToInt(),
                        Username   = username,
                        CreatedAt  = now,
                        StatusId   = Status.Active.ToInt()
                    };
                    var accountId = await AddAsync(account);

                    var accountDevice = new AccountDeviceAddSchema {
                        AccountId  = accountId,
                        DeviceId   = signupModel.DeviceId,
                        DeviceName = signupModel.DeviceName,
                        DeviceType = signupModel.DeviceType,
                        CreatedAt  = now,
                        StatusId   = Status.Active.ToInt()
                    };
                    var deviceId = await _accountDeviceService.AddAsync(accountDevice);

                    var accountProfile = new AccountProfileAddSchema {
                        AccountId = accountId,
                        LinkedId  = string.IsNullOrWhiteSpace(signupModel.Email) ? signupModel.Phone : signupModel.Email,
                        TypeId    = string.IsNullOrWhiteSpace(signupModel.Email) ? AccountProfileType.Phone.ToInt() : AccountProfileType.Email.ToInt(),
                        CreatedAt = now,
                        StatusId  = Status.Active.ToInt()
                    };
                    await _accountProfileService.AddAsync(accountProfile);

                    transaction.Complete();

                    var token = _jwtHandler.Bearer(new Account(accountId, deviceId, username, now).ToClaimsIdentity());
                    return(DataTransferer.Ok(token));
                }
                catch (Exception ex) {
                    var errmsg = "Something went wrong.";
                    Log.Error(ex, errmsg);
                    return(DataTransferer.InternalServerError(ex));
                }
            }
        }
Exemple #4
0
        public void AddUserFromBinding(SignupBindingModel model)
        {
            var user = new User()
            {
                Email    = model.Email,
                Password = model.Password
            };

            this.context.Users.Add(user);
            this.context.SaveChanges();
        }
Exemple #5
0
        public static async Task SignupAsync(SignupBindingModel model)
        {
            var client = new RestClient(Configuration.MySeriesApiBaseAddress);

            var request = new RestRequest("/api/account/create", Method.POST);

            request.AddParameter("application/json; charset=utf-8", Json.StringifyAsync(model), ParameterType.RequestBody);

            var response = await client.Execute(request);

            //TODO error handling
        }
        public IActionResult Signup(SignupBindingModel model, HttpResponse response)
        {
            using (PizzaMoreMVCContext context = new PizzaMoreMVCContext())
            {
                User userEntity = new User()
                {
                    Email    = model.SignUpEmail,
                    Password = model.SignUpPassword
                };

                context.Users.Add(userEntity);
                context.SaveChanges();
            }
            this.Redirect(response, "/home/index");
            return(null);
        }
Exemple #7
0
        public IActionResult Post(SignupBindingModel model)
        {
            bool isValid = true;
            ErrorsSignupBindingModel errors = new ErrorsSignupBindingModel();

            if (string.IsNullOrEmpty(model.UserName))
            {
                errors.username = "******";
                isValid         = false;
            }
            if (!isValid)
            {
                return(BadRequest(new { errors, isValid }));
            }

            return(Ok(new { success = true }));
            //return View();
        }
Exemple #8
0
        public void Signup()
        {
            var user = new SignupBindingModel {
                Email           = "*****@*****.**",
                Password        = "******",
                ConfirmPassword = "******",
                DeviceId        = Guid.NewGuid().ToString(),
                DeviceName      = "DeviceName",
                DeviceType      = "DeviceType"
            };
            var result = _accountService.SignupAsync(user).GetAwaiter().GetResult();

            Console.WriteLine(result.Code);
            Console.WriteLine(result.Data);

            Assert.IsTrue(result.Code == 200);
            Assert.IsTrue(result.Data != null);
        }
Exemple #9
0
        public ActionResult Signup(SignupBindingModel signupInfo)
        {
            if (!ModelState.IsValid)
            {
                return(View(signupInfo));
            }
            if (signupInfo.FirstName != null)
            {
                signupInfo.FirstName = StringUtility.Titlify(signupInfo.FirstName);
            }
            if (signupInfo.LastName != null)
            {
                signupInfo.LastName = StringUtility.Titlify(signupInfo.LastName);
            }
            DateTime now = DateTime.UtcNow;

            try
            {
                WebSecurity.CreateUserAndAccount(
                    signupInfo.Email.ToLower(),
                    signupInfo.Password,
                    new
                {
                    Name          = signupInfo.FirstName == null ? signupInfo.LastName : signupInfo.LastName == null ? signupInfo.FirstName : string.Join(" ", signupInfo.LastName, signupInfo.FirstName),
                    FirstName     = signupInfo.FirstName,
                    LastName      = signupInfo.LastName,
                    Gender        = signupInfo.Gender,
                    Birthday      = signupInfo.Birthday,
                    LastEventDate = now,
                    LastLoginDate = now,
                    CreatedDate   = now,
                    ModifiedDate  = now
                });
                WebSecurity.Login(signupInfo.Email, signupInfo.Password);
                return(RedirectToLocal());
            }
            catch (MembershipCreateUserException ex)
            {
                ModelState.AddModelError(string.Empty, ResourceHelper.GetMembershipCreateStatusText(ex.StatusCode));
            }
            return(View(signupInfo));
        }
Exemple #10
0
        public async Task <ActionResult> OAuthLoginConfirmation(SignupBindingModel model, string returnUrl, CancellationToken cancellationToken)
        {
            ModelState.Remove("Password");
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExtraData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }
            if (ModelState.IsValid)
            {
                var user = await _manager.FindByEmailAsync(model.Email, cancellationToken);

                if (user == null)
                {
                    await _manager.CreateAsync(new UserItem
                    {
                        Email         = MailAddressItem.Create(model.Email, model.FirstName == null ? model.LastName : model.LastName == null ? model.FirstName : string.Join(" ", model.LastName, model.FirstName)),
                        LastName      = model.LastName,
                        FirstName     = model.FirstName,
                        Gender        = model.Gender,
                        Birthday      = model.Birthday,
                        LastIPAddress = Request.UserHostAddress,
                        LastLoginDate = DateTime.UtcNow
                    }, cancellationToken);

                    OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.Email);
                    OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                    return(RedirectToLocal(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("UserName", IdentityAppResources.MembershipCreateStatus_DuplicateUserName);
                }
            }
            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginBindingModel model, string returnUrl)
        {
            // Get the information about the user from the external login provider
            var loginInfo = await OwinAuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login", new { error = "external-login-failure" }));
            }
            // Override the external login info with the values supplyed by the user.
            var signupModel = new SignupBindingModel
            {
                Email = model.Email,
                Name  = model.Name,
            };

            var loginHelper = new LoginHelper(OwinUserManager, OwinAuthenticationManager);

            // Create the user account
            var user = await loginHelper.Signup(signupModel, loginInfo, this.GetExtId(), Request.Url);

            var error = loginHelper.InspectErrorAfterSignup(user);

            if (String.IsNullOrEmpty(error))
            {
                if (String.IsNullOrEmpty(returnUrl))
                {
                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    return(RedirectToLocal(returnUrl));
                }
            }
            else
            {
                ModelState.AddModelError("", error);
                //return View("Signup");
                return(View("ExternalLoginConfirmation", model));
            }
        }
Exemple #12
0
        /// <summary>
        /// Creates a new user and writes it to the database. Creates avatars. Sends email.
        /// </summary>
        /// <param name="model">Comes from the manually filled form. May be null</param>
        /// <param name="loginInfo">Comes from external provider, like Facebook or Google. May be null</param>
        /// <param name="extId">Ideally extId is assigned from the ExtIdCookieName cookie value. It may be null</param>
        /// <param name="currentRequestUri">It is used to determine the server address (production/development) where the confirmation link should point</param>
        /// <returns></returns>
        public async Task <ApplicationUser> Signup(SignupBindingModel model, ExternalLoginInfo loginInfo, string extId, Uri currentRequestUri)
        {
            var user = await InternalSignup(model, loginInfo, extId);

            var error = InspectErrorAfterSignup(user);

            if (String.IsNullOrEmpty(error))
            {
                // We await here. Otherwise error: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context.
                var confirmationToken = await this.userManager.GenerateEmailConfirmationTokenAsync(user.Id);

                // Send confirmation. Do not send in the background to avoid showing the confirmation page if the email actually failed.
                var taskEmail = SendConfirmationEmail(user.Email, user.Id, model.Name, confirmationToken, currentRequestUri);
                // Sign in the user.
                var taskSignin = Sigin(user, false);
                // Create a large and a small identicons and save them into the blob storage.
                var taskAvatarLarge = AccountUtils.CreateAndSaveIdenticonAsync(user.Id, AccountUtils.AvatarLargeSize, AzureStorageUtils.ContainerNames.AvatarsLarge);
                var taskAvatarSmall = AccountUtils.CreateAndSaveIdenticonAsync(user.Id, AccountUtils.AvatarSmallSize, AzureStorageUtils.ContainerNames.AvatarsSmall);
                // Perform the tasks in parallel.
                await Task.WhenAll(taskEmail, taskSignin, taskAvatarLarge, taskAvatarSmall);
            }

            return(user);
        }
        public IHttpActionResult /*HttpResponseMessage*/ Post(SignupBindingModel model)
        {
            bool isValid = true;
            ErrorsSignupBindingModel errors = new ErrorsSignupBindingModel();

            if (string.IsNullOrEmpty(model.UserName))
            {
                errors.username = "******";
                isValid         = false;
            }
            if (string.IsNullOrEmpty(model.Email))
            {
                errors.email = "This field is required";
                isValid      = false;
            }
            try
            {
                MailAddress emailAddress = new MailAddress(model.Email);
            }
            catch
            {
                errors.email = "Email is invalid";
                isValid      = false;
            }
            if (string.IsNullOrEmpty(model.Password))
            {
                errors.password = "******";
                isValid         = false;
            }
            if (!model.Password.Equals(model.PasswordConfirmation))
            {
                errors.passwordConfirmation = "Passwords must match";
                isValid = false;
            }
            if (string.IsNullOrEmpty(model.Timezone))
            {
                errors.timezone = "This field is required";
                isValid         = false;
            }
            SignupResultModel result = new SignupResultModel
            {
                errors  = errors,
                isValid = isValid
            };

            if (!isValid)
            {
                return(Content(HttpStatusCode.BadRequest, result));
            }
            //return Request.CreateResponse(HttpStatusCode.BadRequest, result);

            HttpClient client     = new HttpClient();
            string     jsonObject = JsonConvert.SerializeObject(new
            {
                Email           = model.Email,
                Password        = model.Password,
                ConfirmPassword = model.Password
            });

            var request = HttpContext.Current.Request;
            var url     = request.Url.GetLeftPart(UriPartial.Authority) +
                          request.ApplicationPath + "/api/Account/Register";
            var content  = new StringContent(jsonObject, Encoding.UTF8, "application/json");
            var response = client.PostAsync(url, content).Result;

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(Content(HttpStatusCode.BadRequest, result));
            }

            ICryptoService cryptoService = new PBKDF2();
            //save this salt to the database
            string salt = cryptoService.GenerateSalt();
            //save this hash to the database
            string hashedPassword = cryptoService.Compute(model.Password);

            SignupUser signup = new SignupUser
            {
                Email        = model.Email,
                Password     = hashedPassword,
                PasswordSalt = salt,
                Timezone     = model.Timezone,
                UserName     = model.UserName
            };

            try
            {
                using (ApplicationDbContext context = new ApplicationDbContext())
                {
                    context.SignupUser.Add(signup);
                    context.SaveChanges();
                    return(Content(HttpStatusCode.OK, new { success = true }));
                }
            }
            catch (Exception ex)
            {
                return(Content(HttpStatusCode.InternalServerError, new { error = ex }));
            }


            //return Request.CreateResponse(HttpStatusCode.OK, new { success=true });
        }
Exemple #14
0
        private async Task <ApplicationUser> InternalSignup(SignupBindingModel model, ExternalLoginInfo loginInfo, string extId)
        {
            string email    = null;
            string name     = null;
            string password = null;

            // ExternalLoginInfo comes from an external authentication provider, i.e. Facebook or Google.
            if (loginInfo != null)
            {
                email = loginInfo.Email;
                name  = loginInfo.ExternalIdentity.Name;
            }
            // SignupBindingModel comes filled out manually by the user. Override values from the external service with the manually entered values.
            if (model != null)
            {
                email    = model.Email;
                name     = model.Name;
                password = model.Password;
            }

            if ((String.IsNullOrEmpty(password) && loginInfo == null))
            {
                throw new ArgumentNullException();
            }

            var user = new ApplicationUser
            {
                UserName = email,
                Email    = email,
            };

            var displayName = CoalesceDisplayName(name);

            // The internal Connection Resiliency strategy does not work with user-initiated transactions.
            // The workaround is described in "Limitations with Retrying Execution Strategies" +http://msdn.microsoft.com/en-us/data/dn307226.aspx
            AppDbConfiguration.SuspendExecutionStrategy = true; // try-finally is not needed. The value is stored per request.

            var executionStrategy = new SqlAzureExecutionStrategy();

            await executionStrategy.Execute(
                async() =>
            {
                /* We do not use this.userManager within the Connection Resiliency block.
                 * The DbContext should be constructed within the code block to be retried. This ensures that we are starting with a clean state for each retry.
                 */
                using (var dbContext = new ApplicationDbContext())
                    using (var userStore = new CustomUserStore(dbContext))
                        using (var userManager = new ApplicationUserManager(userStore))
                        {
                            // Reuse the original validators.
                            userManager.UserValidator     = this.userManager.UserValidator;
                            userManager.PasswordValidator = this.userManager.PasswordValidator;

                            /* dbo.appGetNewUserId() generates random Ids and tests them against dbo.aspnetUsers until it finds a vacant one.
                             * Yes, fragmentation in the table increases (it would be somewhat anyway due to editing), bad splits on insert ( but not every time after a page has initially been split in halves).
                             * I believe that after the initial page split many next inserts and edits cause a next split not soon.
                             * So the only harm is about 1/4 extra space (not doubled, because we continue filling pages randomly up until the default fillfactor.)
                             * But the space havily depends on what users put in nvarchars anyway, so to worry about the space is pointless.
                             * Clustered index seeks shouldn't be affected. Splits affect only leaf B-tree pages, branch pages have default fillfactor less than 100% always.
                             * The benefit is we get rid of ExtId nchar(12) in many denormalized tables.
                             * Just to remind, the initial idea behind the original ExtId was to prevent a bad guy from guessing sequecial Ids and download all avatars (avatars are accessable directly as Blobs).
                             * So we sent the true Id to the client plus a separate ExtId for avatar URL and we stored it denormalized in many places.
                             * Now ExtId is just a pre-signup cookie value not used anywhere else.
                             */
                            user.Id = await dbContext.Database.SqlQuery <int>("select dbo.appGetNewUserId();").SingleAsync();

                            using (var transaction = dbContext.Database.BeginTransaction())
                            {
                                // First phase. Create an ASP.NET Identity user in dbo.aspnetUsers
                                var identityResult = String.IsNullOrWhiteSpace(password)
                                 ? await userManager.CreateAsync(user)
                                 : await userManager.CreateAsync(user, password);

                                if (identityResult.Succeeded)
                                {
                                    // Second phase. dbo.appUsers. Postpone the creation of the money account until it is really used.
                                    await dbContext.Database.ExecuteSqlCommandAsync(
                                        "insert dbo.appUsers (Id, DisplayName, ExtId) values (@p0, @p1, @p2);",
                                        user.Id, displayName, extId);

                                    /* The UserManager checks the existence of the username in another connection.
                                     * So in the case of an external authorisation (Google, Facebook) AddLoginAsync() does not see the username created by CreateAsync() in our transaction.
                                     * Using IsolationLevel.ReadUncommitted for our transaction would not help since the UserManager reads with ReadCommitted.
                                     * So we are forced to commit prematurely.
                                     */
                                    transaction.Commit();
                                }
                                else
                                {
                                    transaction.Rollback();
                                }

                                if (identityResult.Succeeded && loginInfo != null)
                                {
                                    identityResult = await userManager.AddLoginAsync(user.Id, loginInfo.Login);
                                }

                                if (!identityResult.Succeeded)
                                {
                                    // A hack to report the error to the caller method. See InspectErrorAfterSignup().
                                    user.Id        = 0;
                                    var dummyClaim = new CustomUserClaim
                                    {
                                        ClaimType  = ClaimTypes.UserData,
                                        ClaimValue = identityResult.PlainErrorMessage("Signup failed.")
                                    };
                                    user.Claims.Add(dummyClaim);
                                }
                            }
                        }
            });

            AppDbConfiguration.SuspendExecutionStrategy = false;

            return(user);
        }
        public async Task <IActionResult> SignupAsync([FromBody] SignupBindingModel collection)
        {
            // todo: Captcha

            if (collection == null)
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveEntry().Message]));
            }

            if (string.IsNullOrEmpty(collection?.Username))
            {
                return(BadRequest(_localizer[DataTransferer.DefectiveEmailOrCellPhone().Message]));
            }

            Log.Debug($"A User is trying to register with this data: {JsonConvert.SerializeObject(collection)}");
            collection.Username = collection.Username.Trim();

            try {
                if (collection.Username.IsPhoneNumber())
                {
                    collection.Phone = collection.Username;
                    if (await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema {
                        LinkedId = collection.Phone
                    }).ConfigureAwait(true) != null)
                    {
                        return(BadRequest(_localizer[DataTransferer.CellPhoneAlreadyExists().Message]));
                    }
                }
                else if (new EmailAddressAttribute().IsValid(collection.Username))
                {
                    collection.Email = collection.Username;
                    if (await _accountProfileService.FirstAsync(new AccountProfileGetFirstSchema {
                        LinkedId = collection.Email
                    }).ConfigureAwait(true) != null)
                    {
                        return(BadRequest(_localizer[DataTransferer.EmailAlreadyExists().Message]));
                    }
                }
                else
                {
                    return(BadRequest(_localizer[DataTransferer.InvalidEmailOrCellPhone().Message]));
                }

                if (string.IsNullOrEmpty(collection.Password) && string.IsNullOrEmpty(collection.ConfirmPassword))
                {
                    return(BadRequest(_localizer[DataTransferer.DefectivePassword().Message]));
                }

                if (collection.Password != collection.ConfirmPassword)
                {
                    return(BadRequest(_localizer[DataTransferer.PasswordsMissmatch().Message]));
                }

                if (string.IsNullOrEmpty(collection.DeviceId) || string.IsNullOrEmpty(collection.DeviceName))
                {
                    return(BadRequest(_localizer[DataTransferer.UnofficialRequest().Message]));
                }

                var result = await _accountService.SignupAsync(collection).ConfigureAwait(true);

                switch (result.Code)
                {
                case 200:
                    return(Ok(result.Data));

                case 400:
                    return(BadRequest(result.Message));

                case 500:
                default:
                    return(Problem(result.Message));
                }
            }
            catch (Exception ex) {
                Log.Error(ex, ex.Source);
                return(Problem(_localizer[DataTransferer.SomethingWentWrong().Message]));
            }
        }