public async Task <IActionResult> SignUp([FromBody] SignUpRequestModel requestModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            SignUpResponseModel responseModel = await _accountService.SignUpAsync(requestModel);

            if (responseModel.IdentityResult.Succeeded)
            {
                string callbackUrl = CreateCallbackUrl("ConfirmEmail", new { userId = responseModel.Id, code = responseModel.SignUpToken, redirectUrl = requestModel.RedirectUrl });
                await _emailHelper.SendEmailAsync(requestModel.Email, "Confirm your account", $"Please confirm your registration using the link: <a title='Confirmation' href='{callbackUrl}'>link</a>");
            }

            if (!responseModel.IdentityResult.Succeeded)
            {
                foreach (IdentityError error in responseModel.IdentityResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(BadRequest(ModelState));
            }

            return(Ok());
        }
예제 #2
0
        public ActionResult SignUp(IFormCollection collection)
        {
            UserLogin userLogin = HttpContext.Session.Get <UserLogin>("UserLogin");

            if (userLogin != null)
            {
                return(View("Index"));
            }
            else
            {
                string FirstName   = collection["FirstName"].ToString();
                string LastName    = collection["LastName"].ToString();
                string Mobile      = collection["Mobile"].ToString();
                string SignUpEmail = collection["SignUpEmail"].ToString();

                SignUpRequestModel signUpRequestModel = new SignUpRequestModel();
                signUpRequestModel.UserName  = SignUpEmail;
                signUpRequestModel.FirstName = FirstName;
                signUpRequestModel.LastName  = LastName;
                signUpRequestModel.Mobile    = Mobile;

                ConsumeWebAPI     consumeWebAPI     = new ConsumeWebAPI();
                UserLoginResponse userLoginResponse = consumeWebAPI.SignUp(signUpRequestModel);
                if (userLoginResponse.ResponseCode == ResponseCode.Success)
                {
                    ViewData["SignUpMessage"] = "Account has been created. Please check your email to verify your account. Link is valid for only three (3) hours.";
                }
                else if (userLoginResponse.ResponseCode == ResponseCode.Inserted)
                {
                    ViewData["SignUpMessage"] = "Failed to send email. Please contact administrator to verify and activate your account.";
                }
            }
            return(View("Index"));
        }
예제 #3
0
        public IActionResult SignUp([FromBody] SignUpRequestModel request)
        {
            if (ModelState.IsValid)
            {
                PasswordWithSalt pws = HashHelper.Hash(request.password);

                if (_db.Members.Where(member => member.Account == request.account).FirstOrDefault() == null)
                {
                    _db.Members.Add(new Member()
                    {
                        Account  = request.account,
                        Password = pws.password,
                        Salt     = pws.salt
                    });
                }
                else
                {
                    return(Ok(new ResultResponseModel {
                        isSuccess = false, message = "此組帳號已被註冊,請使用其他帳號。"
                    }));
                }

                _db.SaveChanges();

                return(Ok(new ResultResponseModel {
                    isSuccess = true, message = "signed up."
                }));
            }

            return(Ok(new ResultResponseModel {
                isSuccess = false, message = "帳號與密碼皆須至少8個字以上,且須含有英文字母及數字。"
            }));
        }
예제 #4
0
        public async Task <IActionResult> SignUp(SignUpRequestModel model)
        {
            ViewBag.Errors      = string.Empty;
            ViewBag.UserCreated = false;

            try
            {
                if (!ModelState.IsValid)
                {
                    throw new ArgumentException("The model is not valid");
                }
                if (model is null)
                {
                    throw new ArgumentNullException("The model can not be null");
                }

                var result = await _accountService.CreateUserAsync(model);

                ViewBag.UserCreated = result.Succeeded;
            }
            catch (Exception ex)
            {
                ViewBag.Errors = ex.Message;
            }

            return(View());
        }
        public async Task <UserLoginResponse> ReVerifySignUp(SignUpRequestModel ObjSignUpRequestModel)
        {
            UserLoginResponse ObjUserLoginResponse = new UserLoginResponse();

            try
            {
                using (RCS_dbContext context = new RCS_dbContext())
                {
                    UserLogin userLogin = await context.UserLogins.FirstOrDefaultAsync(x => x.UserName.ToUpper().Equals(ObjSignUpRequestModel.UserName.ToUpper()));

                    if (userLogin != null)
                    {
                        userLogin.Status = UserLoginStatus.Verified;
                        if (userLogin.Id > 0)
                        {
                            UserOtp userOtp = await context.UserOtps.FirstOrDefaultAsync(x => x.UserLoginId == userLogin.Id && x.IsExpired == false);

                            if (userOtp != null)
                            {
                                //string OTP = Guid.NewGuid().ToString("n").Substring(0, 8) + "@DCL";
                                UserOtp _userOtp = new UserOtp();
                                userOtp.IsExpired = true;

                                userLogin.Password = GlobalProperties.RandomOTP;
                                //Add new UserOtp
                                _userOtp.UserLoginId        = userLogin.Id;
                                _userOtp.Otp                = userLogin.Password;
                                _userOtp.IsExpired          = false;
                                _userOtp.CreatedByIpaddress = ObjSignUpRequestModel.ActionByIPAddress;
                                _userOtp.CreatedBy          = ObjSignUpRequestModel.ActionByUserID;
                                var UserOTP_EntityEntry = await context.AddAsync(_userOtp);

                                int Response = await context.SaveChangesAsync();

                                if (Response > 0)
                                {
                                    MailOperations mailOperations = new MailOperations();
                                    string         name           = userLogin.FirstName + " " + userLogin.LastName.ToUpper();
                                    if (mailOperations.SendSignUpEmail(new System.Net.Mail.MailAddress(userLogin.UserName, name), _userOtp.Otp))
                                    {
                                        ObjUserLoginResponse.ResponseCode = ResponseCode.Success;
                                    }
                                }
                                else
                                {
                                    ObjUserLoginResponse.ResponseCode = ResponseCode.Inserted;
                                }
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                ObjUserLoginResponse.ResponseCode = ResponseCode.Exception;
                ObjUserLoginResponse.Exception    = ex;
            }
            return(ObjUserLoginResponse);
        }
        public async Task <UserLoginResponse> SignUp(SignUpRequestModel ObjSignUpRequestModel)
        {
            UserLoginResponse ObjUserLoginResponse = new UserLoginResponse();

            try
            {
                using (RCS_dbContext context = new RCS_dbContext())
                {
                    UserLogin userLogin = new UserLogin();
                    userLogin.UserName           = ObjSignUpRequestModel.UserName;
                    userLogin.Password           = GlobalProperties.RandomOTP;
                    userLogin.FirstName          = ObjSignUpRequestModel.FirstName;
                    userLogin.LastName           = ObjSignUpRequestModel.LastName;
                    userLogin.Mobile             = ObjSignUpRequestModel.Mobile;
                    userLogin.Type               = ObjSignUpRequestModel.Type;
                    userLogin.CreatedByIpaddress = ObjSignUpRequestModel.ActionByIPAddress;
                    userLogin.CreatedBy          = ObjSignUpRequestModel.ActionByUserID;

                    var UserLogins_EntityEntry = await context.UserLogins.AddAsync(userLogin);

                    int UserLogins_Response = await context.SaveChangesAsync();

                    if (UserLogins_Response > 0)
                    {
                        ObjUserLoginResponse.UserLogin = await context.UserLogins.AsNoTracking().FirstOrDefaultAsync(a => a.Id == userLogin.Id);

                        UserOtp userOtp = new UserOtp();
                        userOtp.UserLoginId        = ObjUserLoginResponse.UserLogin.Id;
                        userOtp.Otp                = userLogin.Password;
                        userOtp.CreatedByIpaddress = ObjSignUpRequestModel.ActionByIPAddress;
                        userOtp.CreatedBy          = ObjSignUpRequestModel.ActionByUserID;

                        var UserOTP_EntityEntry = await context.AddAsync(userOtp);

                        int UserOTP_Response = await context.SaveChangesAsync();

                        if (UserOTP_Response > 0)
                        {
                            ObjUserLoginResponse.ResponseCode = ResponseCode.Inserted;
                            MailOperations mailOperations = new MailOperations();
                            string         name           = userLogin.FirstName + " " + userLogin.LastName.ToUpper();
                            if (mailOperations.SendSignUpEmail(new System.Net.Mail.MailAddress(userLogin.UserName, name), userOtp.Otp))
                            {
                                ObjUserLoginResponse.ResponseCode = ResponseCode.Success;
                            }
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                ObjUserLoginResponse.ResponseCode = ResponseCode.Exception;
                ObjUserLoginResponse.Exception    = ex;
            }
            return(ObjUserLoginResponse);
        }
예제 #7
0
        public async Task <ApiResponse> SignUp(SignUpRequestModel model)
        {
            await _signUpUserCommand.Execute(new SignUpUserCommandArgs
            {
                Email    = model.Email.Trim(),
                Password = model.Password
            });

            return(ApiResponse.Success());
        }
예제 #8
0
        public async Task SignUp(SignUpRequestModel signUpRequest)
        {
            var auth = new FirebaseAuthProvider(new FirebaseConfig(ApiKey));

            signUpRequest.Password.First().CreationTime      = DateTime.Now;
            signUpRequest.Password.First().IsCurrentPassword = true;

            await auth.CreateUserWithEmailAndPasswordAsync(signUpRequest.Email, signUpRequest.Password.First().Password, signUpRequest.Name, true);

            await Client.PushAsync("InternalUsers/", signUpRequest);
        }
예제 #9
0
 public UserLoginResponse ReVerifySignUp(SignUpRequestModel signUpRequestModel)
 {
     try
     {
         string            URL               = GlobalProperties.WebAPI_URL + "/UserLogin/ReVerifySignUp";
         string            Response          = string.Empty;
         UserLoginResponse userLoginResponse = new UserLoginResponse();
         userLoginResponse = (UserLoginResponse)iWebServiceConsumer.ConsumeJsonWebService(URL, signUpRequestModel, userLoginResponse, GlobalProperties.WebAPI_Timeout, out Response);
         return(userLoginResponse);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #10
0
        public async Task <User> AddUser(SignUpRequestModel model)
        {
            User user = new User
            {
                Email       = model.Email,
                FirstName   = model.FirstName,
                LastName    = model.LastName,
                Password    = PasswordHasher.HashPassword(model.Password),
                PhoneNumber = model.PhoneNumber
            };

            await AddAsync(user);

            return(user);
        }
예제 #11
0
 public ApplicationUser MapSignUpRequestModelToDomain(SignUpRequestModel model)
 {
     try
     {
         return(new ApplicationUser
         {
             UserName = $"{model.UserName.Replace(" ", "")}_{Guid.NewGuid()}",
             Email = model.Email,
             UsedExternalProvider = false,
         });
     }
     catch (Exception)
     {
         throw;
     }
 }
예제 #12
0
        public async Task <BaseResponseModel> SignUpAsync(string firstName, string lastName, string companyName, string email, string password, string confirmPassword, int role, string base64Img)
        {
            var requestModel = new SignUpRequestModel
            {
                Email           = email,
                FirstName       = firstName,
                LastName        = lastName,
                CompanyName     = companyName,
                Password        = password,
                ConfirmPassword = confirmPassword,
                Role            = role,
                Base64Img       = base64Img
            };

            return(await requestProvider.PostAsync <BaseResponseModel>(SignUpEndpoint, requestModel));
        }
        public async Task <SignUpResponseModel> SignUpAsync(SignUpRequestModel requestModel)
        {
            ApplicationUser     user          = requestModel.MapToEntity(new ApplicationUser());
            SignUpResponseModel responseModel = new SignUpResponseModel();

            responseModel.IdentityResult = await _userManager.CreateAsync(user, requestModel.Password);

            if (responseModel.IdentityResult.Succeeded)
            {
                responseModel.Id          = user.Id;
                responseModel.SignUpToken = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                return(responseModel);
            }

            return(responseModel);
        }
예제 #14
0
        public ResponseModel RegisterUser(SignUpRequestModel input)
        {
            var response = new ResponseModel();

            if (!this.ModelState.IsValid)
            {
                response.Status = new Status
                {
                    Code = Status.INTERNAL_MESSAGE_CODE,
                    Message = this.ModelState.Values.First().Errors.First().ErrorMessage
                };

                return response;
            }

            if (input == null)
            {
                response.Status = Status.MISSING_PARRAMETERS;
                return response;
            }

            ////check for exist user in db by email
            var existUser = this.Users.SingleOrDefault(a => a.Email == input.Email);
            if (existUser != null)
            {
                response.Status = Status.SIGNUP_HAS_ACCOUNT_YET;
                return response;
            }

            this.Users.Add(new User
            {
                FirstName = input.FirstName,
                LastName = input.LastName,
                Email = input.Email,
                Phone = input.Phone,
                FanApps = input.FanApp,
                Gender = input.Gender,
                City = input.City,
                Address = input.Address,
                CreateDatetime = DateTime.Now,
                Token = AuthenticationUtil.Encrypt(input.Password)
            });

            response.Status = Status.SIGNUP_SUCCESS;
            return response;
        }
예제 #15
0
        public ResultInfo Registration([FromBody] SignUpRequestModel model)
        {
            var data = _authHelper.RegistrationUser(new RegistrationRequestModel <SiteAuthModel>
            {
                Data = new SiteAuthModel
                {
                    Email    = model.Login,
                    Password = model.Password
                },
                Groups = new[] { Enums.Group.User }
            });

            return(new ResultInfo <Guid>
            {
                Data = data.User.Id,
                Code = ResponseResult.Success.Code.CodeString
            });
        }
예제 #16
0
        public async Task <IActionResult> SignUp([FromBody] SignUpRequestModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    await userService.AddUser(model);
                    await SaveAsync();

                    return(ApiResult(true));
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }

            return(Error(ModelState));
        }
        private async Task <User> UserFromSignUpModel(SignUpRequestModel model, string aspNetUserId)
        {
            var now = DateTime.Now;

            return(new User {
                AspNetId = aspNetUserId,
                Banned = false, Listed = true, Active = true,                 // These default values could be managed better than hardcoded here
                Since = now, LastVisit = now,
                FirstName = model.FirstName, LastName = model.LastName,
                KnowsId = model.Knows, LearnsId = model.Learns,
                Knows2Id = model.Knows2, Learns2Id = model.Learns2,
                Knows3Id = model.Knows3, Learns3Id = model.Learns3,
                Gender = model.Gender,
                BirthYear = model.BirthYear, BirthMonth = model.BirthMonth,
                CountryId = model.Country, Location = model.Location,
                Introduction = model.Introduction,
                Tags = await UserTagsFromSignUpModel(model)
            });
        }
        private async Task <ICollection <UsersTagsValue> > UserTagsFromSignUpModel(SignUpRequestModel model)
        {
            var userTags            = new List <UsersTagsValue>();
            Func <int, Task> addTag = async(id) => { userTags.Add(await Entity.UsersTagsValues.FirstOrDefaultAsync(t => t.Id == id)); };

            await addTag(UserTags.AgreeWithTermsOfUse);             // Not cool: This isn't exactly the concern of this method to define whether the use agrees with the terms of use or not.

            if (model.IsSharedTalkMember)
            {
                await addTag(UserTags.FormerSharedTalkMember);
            }
            if (model.IsLivemochaMember)
            {
                await addTag(UserTags.LivemochaMember);
            }
            if (model.IsSharedLingoMember)
            {
                await addTag(UserTags.SharedLingoMember);
            }
            if (model.LookToLearnWithGames)
            {
                await addTag(UserTags.LookToLearnWithGames);
            }
            if (model.LookToLearnWithMore)
            {
                await addTag(UserTags.LookToLearnWithMore);
            }
            if (model.LookToLearnWithTextChat)
            {
                await addTag(UserTags.LookToLearnWithTextChat);
            }
            if (model.LookToLearnWithVoiceChat)
            {
                await addTag(UserTags.LookToLearnWithVoiceChat);
            }
            if (model.WantsToHelpHellolingo)
            {
                await addTag(UserTags.WantsToHelpHellolingo);
            }
            return(userTags);
        }
예제 #19
0
        public async Task <IActionResult> SignUp([FromBody] SignUpRequestModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var result = await _authService.SignUp(model.UserName, model.Email, model.Password);

            return(result.Result
                ? Ok(new SignUpResultModel
            {
                Result = result.Result,
                Errors = result.Errors
            })
                : BadRequest(new SignUpResultModel
            {
                Result = result.Result,
                Errors = result.Errors
            }));
        }
        public async Task <IActionResult> Post([FromBody] SignUpRequestModel signUpRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    Success = false,
                    Message = "Validation error-all fields are required, with a valid email format"
                }));
            }

            try
            {
                var response = await _mediator.Send(signUpRequest);

                return(Created("api/customer", new PayloadedResponse <SignUpResponseModel>
                {
                    Data = response,
                    Message = "Signup completed successfully",
                    Success = true
                }));
            }
            catch (ArgumentException ex)
            {
                return(BadRequest(new Response
                {
                    Success = false,
                    Message = ex.Message
                }));
            }
            catch (Exception ex)
            {
                return(StatusCode(500, new ErrorResponse
                {
                    Errors = { ex },
                    Success = false,
                    Message = ex.Message
                }));
            }
        }
예제 #21
0
        public ActionResult VerifySignUp(IFormCollection collection)
        {
            UserLogin userLogin = HttpContext.Session.Get <UserLogin>("UserLogin");

            if (userLogin != null)
            {
                return(View("Index"));
            }
            else
            {
                string LoginEmail = collection["Email"].ToString();
                string Mobile     = collection["Mobile"].ToString();
                if (!string.IsNullOrEmpty(LoginEmail))
                {
                    if (LoginEmail.Length > 3)
                    {
                        if (LoginEmail.Contains("@"))
                        {
                            SignUpRequestModel signUpRequestModel = new SignUpRequestModel();
                            signUpRequestModel.UserName          = LoginEmail;
                            signUpRequestModel.Mobile            = Mobile;
                            signUpRequestModel.ActionByIPAddress = GlobalProperties.IP_Address;

                            ConsumeWebAPI     consumeWebAPI     = new ConsumeWebAPI();
                            UserLoginResponse userLoginResponse = consumeWebAPI.ReVerifySignUp(signUpRequestModel);
                            if (userLoginResponse.ResponseCode == ResponseCode.Success)
                            {
                                ViewData["SignUpMessage"] = "Verification Email has been regenerated. Please check your email to verify your account. Link is valid for only three (3) hours.";
                            }
                            else if (userLoginResponse.ResponseCode == ResponseCode.Inserted)
                            {
                                ViewData["SignUpMessage"] = "Failed to send email. Please contact administrator to verify and activate your account.";
                            }
                        }
                    }
                }
            }
            return(View("Index"));
        }
예제 #22
0
        public async Task <IActionResult> SignUp([FromBody] SignUpRequestModel model)
        {
            if (ModelState.IsValid)
            {
                SignUpActionResult result = await _accountService.SignUpActionAsync(model.Email, model.Password);

                if (result == SignUpActionResult.Success)
                {
                    _antiforgery.AddAntiforgeryCookies(HttpContext);

                    return(Ok());
                }

                ModelState.AddModelError(nameof(SignUpRequestModel.Email), Strings.ErrorMessage_Email_InUse);
            }

            return(BadRequest(new SignUpResponseModel
            {
                ExpectedError = true,
                ModelState = new SerializableError(ModelState)
            }));
        }
        public async Task <SignUpResponseModel> SignUp(SignUpRequestModel model)
        {
            // Get DeviceTag
            var deviceTagResult = LocalDeviceTag;

            if (deviceTagResult.HasLogTag(LogTag.MissingDeviceTag))
            {
                Log.Reports(deviceTagResult.Reports, Request);
                return(SignUpResponseModel.InvalidEntry);
            }
            var deviceTag = deviceTagResult.Value;

            //Get IpAddress
            var clientIpAddress = NetHelper.GetClientIpAddressFrom(Request);

            // Validate model
            if (ModelState.IsValid == false)
            {
                Log.Error(LogTag.InvalidSignUpModelState, Request, new { message = ModelState.Values, model });
                return(SignUpResponseModel.InvalidEntry);
            }
            // Verify email isn't already used
            if ((await UserManager.FindByNameAsync(model.Email)) != null)
            {
                Log.Info(LogTag.SignUpEmailAlreadyInUse, Request, new { model.Email });
                return(SignUpResponseModel.EmailAlreadyInUse);
            }
            // Create AspNet user
            var aspNetUser = new AspNetUser {
                UserName = model.Email, Email = model.Email, UiCulture = System.Threading.Thread.CurrentThread.CurrentUICulture.Name
            };
            var result = await UserManager.CreateAsync(aspNetUser, model.Password);

            if (!result.Succeeded)
            {
                Log.Error(LogTag.AspNetUserCreationError, Request, new { result.Errors });
                return(SignUpResponseModel.UnhandledIssue);
            }

            // Regulate new user
            var user = await UserFromSignUpModel(model, aspNetUser.Id);

            IAccountRegulator regulator = Injection.Kernel.Get <IAccountRegulator>();
            var logReports = regulator.RegulateNewUser(model.Email, model.Password, user, deviceTag, clientIpAddress);

            Log.Reports(logReports, Request);

            //Save Hellolingo user profile
            var newUser = await StoreNewUser(user);

            if (newUser == null)
            {
                Log.Error(LogTag.SignUpUserCreationReturnedNull, Request, new { aspNetUser, model });
                await UserManager.DeleteAsync(aspNetUser);

                return(SignUpResponseModel.UnhandledIssue);
            }

            // Complete non-critical sign up process
            try {
                // Link device to new user
                var ipV4 = NetHelper.GetClientIpAddressAsUIntFrom(Request);
                await DeviceTagManager.LinkDeviceToUser(deviceTag, newUser.Id);

                // Send Email Verification
                if (newUser.StatusId == UserStatuses.PendingEmailValidation)
                {
                    await SendConfirmationEmailAsync(aspNetUser, newUser, aspNetUser.Email);
                }

                // Add Welcome Mail
                string message;
                switch (CultureHelper.GetCurrentCulture())
                {
                case "fr": message = "\n\nNous sommes ravis de vous compter comme nouveau membre de notre communauté. Nous vous recommandons d’explorer la fonction de recherche de partenaires linguistiques et d’envoyer autant d'emails que vous le souhaitez à des partenaires potentiels. Ils vous répondront ici dans votre messagerie. Vous pouvez aussi vous rendre dans la section de chat vocal et textuel pour commencer à pratiquer tout de suite dans les salons de chat publiques et privés (la fonction chat vocal est disponible en conversation privée)." +
                                     "\n\nSi vous avez des soucis, des questions ou des idées, n’hésitez pas à nous contacter via le formulaire de contact ou en répondant directement à cet email. HelloLingo est votre communauté et nous comptons sur vous pour la garder conviviale.Veillez à vous en servir dans un but d’apprentissage linguistique uniquement, soyez respectueux et pensez à reporter les bugs et dérangements quand vous les voyez. C’est la meilleure façon de protéger et d’améliorer HelloLingo." +
                                     "\n\nApprenez et prospérez !\nL’équipe HelloLingo"; break;

                case "de": message = "\n\nWir sind erfreut, dich als neues Mitglied unserer Sprachlern - Gemeinschaft zu begrüßen. Wir empfehlen dir die Finden - Funktion zu erkunden und so viele Emails an potentielle Partner zu versenden wie du möchtest. Sie werden dir genau hier antworten, in deiner Mailbox. Du kannst auch zum Text & Voice Chat gehen und sofort beginnen, in öffentlichen oder privaten Räumen zu lernen. Voice Chat Unterhaltungen können von einem beliebigen privaten Raum gestartet werden." +
                                     "\n\nSolltest du Probleme, Fragen oder Anregungen haben, lass es uns bitte wissen. Dafür kannst du das Kontaktformular benutzen oder direkt auf diese Email antworten. Hellolingo ist deine Community und wir zählen auf deinen Beitrag dazu, dass sie großartig bleibt. Bitte verwende sie nur zum Sprachen lernen, sei rücksichtsvoll und denke darüber nach, Störungen oder Fehler zu melden, sobald du sie siehst.Das ist der beste Weg, um Hellolingo zu bewahren und zu verbessern." +
                                     "\n\nLearn and prosper!\nThe Hellolingo Team"; break;

                case "ko": message = "\n\n우리는 귀하가 언어습득 모임의 새 회원이 되신것을 매우 반갑게 생각합니다. 당신이 우리의 다양한 기능을 탐색해 보고 잠재적 파트너에게 많은 이메일을 보내시는것을 추천합니다. 그들은 당신의 메일박스에 회신할 것입니다. 또한 텍스트&보이스 채팅에서 오픈된 혹은 개인적 채팅룸에서 즉시 연습하실수 있습니다. " +
                                     "\n\n만일 다른 사항, 질문 혹은 아이디어가 있으시면 이 이메일로 회신을 주시면 감사하겠습니다. Hellolingo는 당신의 커뮤니티이고 항상 멋지게 유지되길 기대하고 있습니다. 반드시 이 사이트는 언어를 배우는 것으로만 사용해 주시고 다른이들을 배려하며 불편사항이나 버그를 발견하시면 말씀해 주시기 바랍니다. 이것은 Hellolingo를 보호하고 발전시키는 가장 좋은 방법입니다. " +
                                     "\n\n배우고 발전하자!\nHellolingo 팀 드림"; break;

                case "nl": message = "\n\nWe zijn heel verheugd om jou als een nieuwe deelnemer in onze gemeenschap te mogen verwelkomen.We raden je aan om vooral de find feature uit te proberen, en zoveel mogelijk e - mails te versturen naar potentiele partners.Ze zullen je hier beantwoorden, in jouw mailbox. Je kan ook naar de tekst&voice chat gaan en direct beginnen met oefenen in publieke of privé kamers. Chats met voice gesprekken kunnen geïnitieerd worden vanuit elke privé kamer." +
                                     "\n\nAls je enige problemen, vragen of ideeën hebt, laat het ons alstublieft weten via onze contact formulier, of door direct op deze e-mail te reageren. Hellolingo is jouw gemeenschap en we rekenen op jou om het aangenaam te houden.Zorg ervoor dat je het alleen gebruikt om talen te oefenen, altijd rekening houdt met anderen en niet vergeet om onderbrekingen en bugs te rapporteren wanneer je die ervaart. Dit is de beste manier waarop Hellolingo beschermt en verbetert kan worden." +
                                     "\n\nLeer en wees succesvol!\nHet Hellolingo Team"; break;

                case "zh-CN": message = "\n\n非常开心你能加入我们的语言学习社区。我们希望你能尽可能的去探索和尝试各种功能,你可以随时发邮件给你的潜在语言搭档,他们的回复会出现在你的邮箱里。你也可以使用文本 & 语音聊天功能在公共聊天室或者私人聊天室立刻开始进行你的语言练习。任何私人聊天室都是可以进行语音对话的。" +
                                        "\n\n如果你有任何疑问, 建议或者想法,请随时通过上述联系方式来联系我们。hellolingo是属于你的语言社区,你有责任把它变的越来越好,不是吗?:-)同时,我们希望你在这里进行的只有语言学习这一件事,也请在学习的同时,去关心和体谅他人。如果你遇到了任何bug,请及时反馈给我们,这是让hellolingo能更好的为你服务的最佳方式。" +
                                        "\n祝:学习进步,生活开心。\n\nhellolingo团队敬上"; break;

                default: message = "\n\nWe're thrilled to have you as a new member of our language learning community. We recommend you to explore the Find feature and send as many emails as you want to potential partners. They'll reply to you right here, in you mailbox. You can also go to the Text & Voice chat and start practicing immediately in public or private rooms. Voice chat conversations can be initiated from any private room." +
                                   "\n\nIf you have any issues, questions or ideas, please let us know from the contact form or by replying to this email directly. Hellolingo is your community and we count on you to keep it awesome. Make sure to use it for language learning only, always be considerate of others and think about reporting disruptions or bugs when you see them. This is the best way to protect and improve Hellolingo." +
                                   "\n\nLearn and prosper!\nThe Hellolingo Team"; break;
                    //"\n\nP.S.: We're looking to translate this message in the following languages: 日本語. Email us if you can help.";
                }
                Entity.Mails.Add(new Mail {
                    When             = DateTime.Now,
                    FromId           = 1, ToId = user.Id, FromStatus = MailStatuses.Deleted, ToStatus = MailStatuses.New,
                    RegulationStatus = MailRegulationStatuses.ManualPass, NotifyStatus = NotifyStatuses.Blocked,
                    Subject          = "Welcome to Hellolingo!", Message = message, ReplyToMail = null
                });
                await Entity.SaveChangesAsync();
            } catch (Exception ex) {
                Log.Error(LogTag.CompletingSignUpFailed, Request, new { aspNetUser, model, ex });
            }

            // Sign new user in
            return(await SignInCreatedUser(aspNetUser.Id));
        }
예제 #24
0
        public async Task <IdentityResult> CreateUserAsync(SignUpRequestModel model)
        {
            try
            {
                if (model is null)
                {
                    throw new Exception("The model to create the user can not be null");
                }

                var user = _accountMapper.MapSignUpRequestModelToDomain(model);

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

                if (!result.Succeeded)
                {
                    throw new Exception(result.Errors.ToList()[0].Description);
                }

                var resultRoleUser = await _userManager.AddToRoleAsync(user, "user");

                if (!resultRoleUser.Succeeded)
                {
                    throw new Exception(resultRoleUser.Errors.ToList()[0].Description);
                }

                if (model.Email == Configuration["AdminEmail"])
                {
                    var resultRoleAdmin = await _userManager.AddToRoleAsync(user, "admin");

                    if (!resultRoleAdmin.Succeeded)
                    {
                        throw new Exception(resultRoleAdmin.Errors.ToList()[0].Description);
                    }
                }

                string token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                if (string.IsNullOrEmpty(token))
                {
                    throw new Exception("The token could not be generated!");
                }

                await SendEmailConfirmationAsync(token, user.Email, user.Id, user.UserName);

                return(result);
            }
            catch (Exception)
            {
                if (model is null)
                {
                    throw;
                }

                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user is null)
                {
                    throw;
                }

                await _userManager.RemoveFromRolesAsync(user, new List <string> {
                    "user", "admin"
                });

                await _userManager.DeleteAsync(user);

                throw;
            }
        }
        private void TestUserInputCleanUp()
        {
            IList <ValidationResult> result;
            //Validate FirstName, LastName, Location cleanUp
            var modelToValidate = new SignUpRequestModel
            {
                BirthMonth               = 4,
                BirthYear                = 1999,
                Country                  = 100,
                Email                    = "*****@*****.**",
                Password                 = "******",
                FirstName                = @"   -\\--  (*@#$%^&*()_+(%^%^&%^$%^$^%$BE'R^\-NARD  \\-- ",
                LastName                 = @" -\\-- (..*@#$%^&*()_+(%^%^&%^$%^$^%$V.ander^\- ydt^$%^$^%...  \- ",
                Location                 = @" &()',  K(y)i&',v ,()'&   ",
                IsSharedTalkMember       = true,
                Gender                   = "F",
                Knows                    = 1,
                Learns                   = 2,
                LookToLearnWithGames     = true,
                LookToLearnWithMore      = true,
                LookToLearnWithTextChat  = true,
                LookToLearnWithVoiceChat = true,
                WantsToHelpHellolingo    = true,
            };

            result = ValidatorHelper.ValidateModel(modelToValidate);
            string expFirstName = @"Ber\-nard";
            string expLastName  = @"V.ander\- ydt...";
            string expLocation  = @"K(y)i&',v";

            Assert.IsTrue(modelToValidate.FirstName == expFirstName,
                          $"First name cleanup is failed. Result: {modelToValidate.FirstName}, expected: {expFirstName}");
            Assert.IsTrue(modelToValidate.LastName == expLastName,
                          $"Last name cleanup is failed. Result: {modelToValidate.LastName}, expected: {expLastName}");
            Assert.IsTrue(modelToValidate.Location == expLocation,
                          $"Location cleanup is failed. Result: {modelToValidate.Location}, expected: {expLocation}");

            //Validate FirstName, LastName, Location cleanUp with only restricted symbols
            var modelToValidateWithRestrictedSymbols = new SignUpRequestModel
            {
                BirthMonth               = 4,
                BirthYear                = 1999,
                Country                  = 100,
                Email                    = "*****@*****.**",
                Password                 = "******",
                FirstName                = @"%^&*()_+(%^%^&%^$%",
                LastName                 = @"$%^&*()_+(%^%^",
                Location                 = @" &()',  ()&', ,()'&   ",
                IsSharedTalkMember       = true,
                Gender                   = "F",
                Knows                    = 1,
                Learns                   = 2,
                LookToLearnWithGames     = true,
                LookToLearnWithMore      = true,
                LookToLearnWithTextChat  = true,
                LookToLearnWithVoiceChat = true,
                WantsToHelpHellolingo    = true,
            };

            result = ValidatorHelper.ValidateModel(modelToValidateWithRestrictedSymbols);
            Assert.IsTrue(result.Count == 2, $"Validation result must be without Errors. Actual: {result.Count} errors. ");
            Assert.IsTrue(result[0].ErrorMessage == $"The field {nameof(modelToValidateWithRestrictedSymbols.FirstName)} is invalid.");
            Assert.IsTrue(result[1].ErrorMessage == $"The field {nameof(modelToValidateWithRestrictedSymbols.LastName)} is invalid.");
            Assert.IsTrue(modelToValidateWithRestrictedSymbols.Location == null, $"Location cleanup is failed. Result: {modelToValidateWithRestrictedSymbols.Location}, expected: null");


            //Validate FirstName, LastName, Location cleanUp with empty strings
            var modelToValidateWithEmptyStrings = new SignUpRequestModel
            {
                BirthMonth               = 4,
                BirthYear                = 1999,
                Country                  = 100,
                Email                    = "*****@*****.**",
                Password                 = "******",
                FirstName                = @"   ",
                LastName                 = @"   ",
                Location                 = @"   ",
                IsSharedTalkMember       = true,
                Gender                   = "F",
                Knows                    = 1,
                Learns                   = 2,
                LookToLearnWithGames     = true,
                LookToLearnWithMore      = true,
                LookToLearnWithTextChat  = true,
                LookToLearnWithVoiceChat = true,
                WantsToHelpHellolingo    = true,
            };

            result = ValidatorHelper.ValidateModel(modelToValidateWithEmptyStrings);
            Assert.IsTrue(result.Count == 2, $"Validation result must be without Errors. Actual: {result.Count} errors. ");
            Assert.IsTrue(result[0].ErrorMessage == $"The field {nameof(modelToValidateWithRestrictedSymbols.FirstName)} is invalid.");
            Assert.IsTrue(result[1].ErrorMessage == $"The field {nameof(modelToValidateWithRestrictedSymbols.LastName)} is invalid.");
            Assert.IsTrue(modelToValidateWithEmptyStrings.Location == null,
                          $"Location cleanup is failed. Result: {modelToValidateWithEmptyStrings.Location}, expected: null");



            //Validate model with Location equals null.
            var modelWithLocationNull = new SignUpRequestModel()
            {
                BirthMonth               = 4,
                BirthYear                = 1999,
                Country                  = 100,
                Email                    = "*****@*****.**",
                Password                 = "******",
                FirstName                = "BERNARD",
                LastName                 = "Vanderydt",
                IsSharedTalkMember       = true,
                Gender                   = "F",
                Knows                    = 1,
                Learns                   = 2,
                LookToLearnWithGames     = true,
                LookToLearnWithMore      = true,
                LookToLearnWithTextChat  = true,
                LookToLearnWithVoiceChat = true,
                WantsToHelpHellolingo    = true,
            };

            var noErrors = ValidatorHelper.ValidateModel(modelWithLocationNull).ToList();

            Assert.IsTrue(noErrors.Count == 0, $"Validation result must be without Errors. Actual: {noErrors.Count} errors. ");
            Assert.IsNull(modelWithLocationNull.Location, "Location must be null");

            //Validate model with Location equals empty string.
            var modelWithLocationEmptyString = new SignUpRequestModel()
            {
                BirthMonth               = 4,
                BirthYear                = 1999,
                Country                  = 100,
                Location                 = "",
                Email                    = "*****@*****.**",
                Password                 = "******",
                FirstName                = "BERNARD",
                LastName                 = "Vanderydt",
                IsSharedTalkMember       = true,
                Gender                   = "F",
                Knows                    = 1,
                Learns                   = 2,
                LookToLearnWithGames     = true,
                LookToLearnWithMore      = true,
                LookToLearnWithTextChat  = true,
                LookToLearnWithVoiceChat = true,
                WantsToHelpHellolingo    = true,
            };

            var noErrorsForEmptyString = ValidatorHelper.ValidateModel(modelWithLocationEmptyString).ToList();

            Assert.IsTrue(noErrorsForEmptyString.Count == 0,
                          $"Validation result must be without errors and equal null. Actual: {noErrorsForEmptyString.Count} errors. ");
            Assert.IsNull(modelWithLocationEmptyString.Location, "Location must be null");
        }
예제 #26
0
        public async Task <ActionResult <UserResponseModel> > signUp(SignUpRequestModel user)
        {
            Users newUserAccount = new Users();

            newUserAccount.MembershipId = user.gymMemberId.Trim();
            newUserAccount.Username     = user.username.Trim();
            newUserAccount.Gym          = await gymRepository.getGymByNameAndBranch(user.gymName.Trim(), user.gymBranch.Trim());

            newUserAccount.GymIdForeignKey = newUserAccount.Gym.GymId;

            GymMember member = await gymMembersRepository.getMember(newUserAccount.MembershipId,
                                                                    newUserAccount.GymIdForeignKey);


            if (member == null)
            {
                return(Unauthorized("This gym member ID does not exist."));
            }

            Users checkIfUserHasAccount = await userGymMovesRepository.getUserByMemberID(member.MembershipId,
                                                                                         member.GymId);

            if (checkIfUserHasAccount != null)
            {
                return(BadRequest("There is already an account for this gym member."));
            }

            newUserAccount.Name        = member.Name;
            newUserAccount.Surname     = member.Surname;
            newUserAccount.PhoneNumber = member.PhoneNumber;
            newUserAccount.Email       = member.Email;

            newUserAccount.UserType = member.UserType;

            Users checkIfUsernameExists = await userGymMovesRepository.getUser(newUserAccount.Username);

            if (checkIfUsernameExists != null)
            {
                return(Unauthorized("This username is already in use."));
            }

            Random random = new Random();

            newUserAccount.Salt = getRandomString(random.Next(5, 10));
            string hash = getHash(SHA256.Create(), user.password + newUserAccount.Salt);

            newUserAccount.Password = hash;

            bool added = await userGymMovesRepository.addUser(newUserAccount);

            if (added)
            {
                NotificationSettings newUserNotifs = new NotificationSettings();

                newUserNotifs.Email              = true;
                newUserNotifs.PushNotifications  = false;
                newUserNotifs.UsernameForeignKey = newUserAccount.Username;
                newUserNotifs.User = newUserAccount;

                added = await notificationSettingRepository.addUser(newUserNotifs);

                UserResponseModel response = new UserResponseModel();
                response.userType    = newUserAccount.UserType;
                response.name        = newUserAccount.Name;
                response.gymMemberID = newUserAccount.MembershipId;
                response.gymID       = newUserAccount.GymIdForeignKey;

                return(Ok(response));
            }
            else
            {
                return(StatusCode(500, "Unable to create this account right now."));
            }
        }