Ejemplo n.º 1
0
        public async Task <Member> CreateNewUser(MemberView memberView)
        {
            if (!EmailChecker.IsValidEmail(memberView.Email))
            {
                throw new CoralTimeDangerException("Invalid email");
            }

            if (memberView.IsAdmin)
            {
                var applicationUserAdmin = new ApplicationUser
                {
                    UserName  = memberView.UserName,
                    Email     = memberView.Email,
                    IsAdmin   = true,
                    IsManager = false,
                    IsActive  = true
                };

                return(await CreateNewUserCommon(memberView, applicationUserAdmin, ApplicationRoleAdmin));
            }
            else
            {
                var applicationUserMember = new ApplicationUser
                {
                    UserName  = memberView.UserName,
                    Email     = memberView.Email,
                    IsAdmin   = false,
                    IsManager = false,
                    IsActive  = true
                };

                return(await CreateNewUserCommon(memberView, applicationUserMember, ApplicationRoleUser));
            }
        }
Ejemplo n.º 2
0
        public MemberView PatchPersonalInfo(string userName, MemberPersonalInfoView memberPreferencesView)
        {
            if (!EmailChecker.IsValidEmail(memberPreferencesView.Email))
            {
                throw new CoralTimeDangerException("Invalid email");
            }

            CheckRelatedEntities(userName, out var memberByName);
            memberByName          = Uow.MemberRepository.GetQueryByUserName(userName);
            memberByName.FullName = memberPreferencesView.FullName;

            try
            {
                Uow.MemberRepository.Update(memberByName);

                Uow.Save();

                _memberService.ChangeEmailByUserAsync(memberByName, memberPreferencesView.Email).GetAwaiter().GetResult();
                _memberService.UpdateUserClaims(memberByName.Id);

                Uow.MemberRepository.LinkedCacheClear();
                return(memberByName.GetView(Mapper));
            }
            catch (Exception e)
            {
                throw new CoralTimeSafeEntityException("An error occurred while updating member", e);
            }
        }
Ejemplo n.º 3
0
        public MemberView PatchPersonalInfo(MemberPersonalInfoView memberPreferencesView)
        {
            if (!EmailChecker.IsValidEmail(memberPreferencesView.Email))
            {
                throw new CoralTimeDangerException("Invalid email");
            }

            if (_isDemo)
            {
                throw new CoralTimeForbiddenException("Full name can't be changed on demo site");
            }

            CheckRelatedEntities(ImpersonatedUserName, out var memberByName);
            memberByName          = Uow.MemberRepository.GetQueryByUserName(ImpersonatedUserName);
            memberByName.FullName = memberPreferencesView.FullName;

            Uow.MemberRepository.Update(memberByName);
            Uow.Save();

            _memberService.ChangeEmailByUserAsync(memberByName, memberPreferencesView.Email).GetAwaiter().GetResult();
            _memberService.UpdateUserClaims(memberByName.Id);

            Uow.MemberRepository.LinkedCacheClear();

            var urlIcon    = _avatarService.GetUrlIcon(memberByName.Id);
            var memberView = memberByName.GetView(Mapper, urlIcon);

            return(memberView);
        }
Ejemplo n.º 4
0
        private static async Task <EmailChecker> QueryLUIS(string Query)
        {
            EmailChecker LUISResult = new EmailChecker();
            var          LUISQuery  = Uri.EscapeDataString(Query);

            using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
            {
                // Get key values from the web.config
                string LUIS_Url = WebConfigurationManager.AppSettings["LUIS_Url"];
                string LUIS_Id  = WebConfigurationManager.AppSettings["LUIS_Id"];
                string LUIS_Subscription_Key = WebConfigurationManager.AppSettings["LUIS_Subscription_Key"];
                string RequestURI            = string.Format("{0}/{1}?subscription-key={2}&verbose=true&timezoneOffset=0&q={3}",
                                                             LUIS_Url, LUIS_Id, LUIS_Subscription_Key, LUISQuery);

                System.Net.Http.HttpResponseMessage msg = await client.GetAsync(RequestURI);

                if (msg.IsSuccessStatusCode)
                {
                    var JsonDataResponse = await msg.Content.ReadAsStringAsync();

                    LUISResult = JsonConvert.DeserializeObject <EmailChecker>(JsonDataResponse);
                }
            }
            return(LUISResult);
        }
Ejemplo n.º 5
0
        public IActionResult Register(UserViewModel model)
        {
            EmailChecker validate = new EmailChecker(_context);

            if (validate.Check(model.email))
            {
                if (ModelState.IsValid)
                {
                    PasswordHasher <User> hasher = new PasswordHasher <User>();
                    User newUser = new User
                    {
                        first_name   = model.first_name,
                        last_name    = model.last_name,
                        email        = model.email,
                        password     = model.password,
                        created_date = DateTime.Now,
                        updated_date = DateTime.Now
                    };
                    newUser.password = hasher.HashPassword(newUser, newUser.password);

                    //Save new user
                    _context.Add(newUser);
                    _context.SaveChanges();

                    return(RedirectToAction("Welcome"));
                }
            }
            else
            {
                ModelState.AddModelError("email", "Please select a unique email.");
            }
            return(View(model));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Добавить почтовые ящики к сообщению для SMTP клиента
        /// </summary>
        /// <param name="emailsList">Список почтовых ящиков</param>
        private void AddEmails(IEnumerable <String> emailsList)
        {
            // Очищаем список почтовых ящиков подлежащих рассылке
            ClearEmails();

            //Добавляем почтовые ящики к рассылке
            foreach (var item in emailsList)
            {
                if (EmailChecker.IsValidEmail(item))
                {
                    mailMessage.To.Add(item);
                }
                else
                {
                    throw new ArgumentException("Incorrect email");
                }
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            /*
             * var emailConnectionsData = new List<EmailConnectionData>
             * {
             *  new EmailConnectionData
             *  {
             *      EmailServerHost = "imap.yandex.ru",
             *      EmailServerPort = 993,
             *      UserName = "******",
             *      Password = new Password("urartukahak859")
             *  },
             *  new EmailConnectionData
             *  {
             *      EmailServerHost = "imap.yandex.ru",
             *      EmailServerPort = 993,
             *      UserName = "******",
             *      Password = new Password("noviyurartukahak859")
             *  }
             * };
             */

            var emailDataWriter = new EmailDataWriter();

            emailDataWriter.WriteConnectionsData(new[] { new EmailConnectionData()
                                                         {
                                                             EmailServerHost = "imap.yandex.ru",
                                                             EmailServerPort = 993,
                                                             UserName        = "******",
                                                             Password        = new Password("noviyurartukahak859")
                                                         } });

            var emailConnectionsData = (IList <EmailConnectionData>) new EmailDataReader().ReadConnectionsData();
            var emailChecker         = new EmailChecker(emailConnectionsData);
            var emailCheckResults    = emailChecker.GetCheckResults();

            emailCheckResults
            .ToList()
            .ForEach(e => {
                Console.WriteLine(e.GetMessage());
            });
            Console.Read();
        }
Ejemplo n.º 8
0
        public static List <SelectItemPair> ReadEmails(string filePath)
        {
            List <SelectItemPair> emails = new List <SelectItemPair>();

            foreach (var line in File.ReadAllLines(filePath))
            {
                var trimmed = StringHelper.Trim(line);
                if (string.IsNullOrEmpty(trimmed))
                {
                    continue;
                }
                if (!EmailChecker.IsValidEmail(trimmed))
                {
                    continue;
                }

                emails.Add(new SelectItemPair()
                {
                    Selected = true, Text = trimmed, Value = trimmed
                });
            }
            return(emails);
        }
Ejemplo n.º 9
0
        public async Task <MemberView> Update(MemberView memberView)
        {
            var memberByName = Uow.MemberRepository.GetQueryByUserName(CurrentUserName);

            if (memberByName == null)
            {
                throw new CoralTimeEntityNotFoundException($"Member with userName {CurrentUserName} not found.");
            }

            if (!memberByName.User.IsActive)
            {
                throw new CoralTimeEntityNotFoundException($"Member with userName {CurrentUserName} is not active.");
            }

            var memberId = memberView.Id;

            if (memberByName.Id != memberId && !memberByName.User.IsAdmin)
            {
                throw new CoralTimeForbiddenException($"Member with userName {CurrentUserName} can't change other user's data.");
            }

            if (!EmailChecker.IsValidEmail(memberView.Email))
            {
                throw new CoralTimeSafeEntityException("Invalid email");
            }

            var member = Uow.MemberRepository.GetQueryByMemberId(memberId);

            if (_isDemo)
            {
                if (member.User.Email != memberView.Email)
                {
                    throw new CoralTimeForbiddenException("Email can't be changed on demo site");
                }
                if (member.User.UserName != memberView.UserName)
                {
                    throw new CoralTimeForbiddenException("Username can't be changed on demo site");
                }
                if (member.User.IsActive != memberView.IsActive)
                {
                    throw new CoralTimeForbiddenException("Status can't be changed on demo site");
                }
                if (member.FullName != memberView.FullName)
                {
                    throw new CoralTimeForbiddenException("Full name can't be changed on demo site");
                }
            }

            if (memberByName.User.IsAdmin)
            {
                var newEmail    = memberView.Email;
                var newUserName = memberView.UserName;
                var newIsActive = memberView.IsActive;
                var newIsAdmin  = memberView.IsAdmin;

                if (member.User.Email != newEmail || member.User.UserName != newUserName || member.User.IsActive != newIsActive || member.User.IsAdmin != newIsAdmin)
                {
                    member.User.Email    = newEmail;
                    member.User.UserName = newUserName;

                    var updateResult = await _userManager.UpdateAsync(member.User);

                    if (updateResult.Succeeded)
                    {
                        var startRole = member.User.IsAdmin ? ApplicationRoleAdmin : ApplicationRoleUser;

                        if (memberId != memberByName.Id)
                        {
                            member.User.IsActive = newIsActive;
                            member.User.IsAdmin  = newIsAdmin;
                        }

                        var finishRole = member.User.IsAdmin ? ApplicationRoleAdmin : ApplicationRoleUser;

                        try
                        {
                            Uow.MemberRepository.Update(member);
                            Uow.Save();

                            if (startRole != finishRole)
                            {
                                await _userManager.RemoveFromRoleAsync(member.User, startRole);

                                await _userManager.AddToRoleAsync(member.User, finishRole);
                            }

                            UpdateUserClaims(member.Id);
                            Uow.MemberRepository.LinkedCacheClear();
                        }
                        catch (Exception e)
                        {
                            throw new CoralTimeDangerException("An error occurred while updating member", e);
                        }
                    }
                    else
                    {
                        CheckMembersErrors(updateResult.Errors.Select(e => new IdentityErrorView
                        {
                            Code        = e.Code,
                            Description = e.Description
                        }));
                    }
                }
            }

            var memberById = Uow.MemberRepository.GetQueryByMemberId(memberId);

            await ChangeEmailByUserAsync(memberById, memberView.Email);

            memberById.FullName                     = memberView.FullName;
            memberById.DefaultProjectId             = memberView.DefaultProjectId;
            memberById.DefaultTaskId                = memberView.DefaultTaskId;
            memberById.DateFormatId                 = memberView.DateFormatId;
            memberById.TimeZone                     = memberView.TimeZone;
            memberById.WeekStart                    = (WeekStart)memberView.WeekStart;
            memberById.IsWeeklyTimeEntryUpdatesSend = memberView.IsWeeklyTimeEntryUpdatesSend;
            memberById.TimeFormat                   = memberView.TimeFormat;
            memberById.SendEmailTime                = memberView.SendEmailTime;
            memberById.SendEmailDays                = ConverterBitMask.DayOfWeekStringToInt(memberView.SendEmailDays);

            try
            {
                Uow.MemberRepository.Update(memberById);

                if (Uow.Save() > 0)
                {
                    UpdateUserClaims(memberById.Id);
                }

                Uow.MemberRepository.LinkedCacheClear();
            }
            catch (Exception e)
            {
                Uow.MemberRepository.LinkedCacheClear();
                throw new CoralTimeDangerException("An error occurred while updating member", e);
            }

            var memberByIdResult = Uow.MemberRepository.LinkedCacheGetById(memberById.Id);
            var result           = memberByIdResult.GetView(Mapper);

            return(result);
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Update([FromBody] UpdateUserViewModel updateUserViewModel)
        {
            var updatedUser = await userManager.Users.Where <User>(c => c.Id == updateUserViewModel.UserId).FirstOrDefaultAsync();

            if (updatedUser != null)
            {
                if (updateUserViewModel.NewUserName != null)
                {
                    updatedUser.UserName = updateUserViewModel.NewUserName;
                }

                if (updateUserViewModel.NewAvatarUrl != null)
                {
                    updatedUser.AvatarUrl = updateUserViewModel.NewAvatarUrl;
                }

                if (updateUserViewModel.NewEmail != null)
                {
                    //Check whether email is existed
                    bool isExisted = await EmailChecker.Check(updateUserViewModel.NewEmail);

                    if (isExisted == false)
                    {
                        return(BadRequest(new
                        {
                            Errors = new { Code = "NotExistedEmailAddress", Description = "Email address is not existed!" }
                        }));
                    }
                    else
                    {
                        updatedUser.Email = updateUserViewModel.NewEmail;
                    }
                }

                if (updateUserViewModel.Description != null)
                {
                    updatedUser.Description = updateUserViewModel.Description;
                }


                var result = await userManager.UpdateAsync(updatedUser);

                if (result.Succeeded)
                {
                    return(Ok(new
                    {
                        Results = updatedUser
                    }));
                }
                else
                {
                    return(BadRequest(new
                    {
                        Errors = result.Errors.ToArray()[0]
                    }));
                }
            }
            else
            {
                return(BadRequest(new
                {
                    Errors = new { Code = "InvalidInputParameters", Description = "Invalid Input Parameters!" }
                }));
            }
        }
        public Dictionary <string, object> Put([FromBody] ClienteOnline newClient)
        {
            if (newClient.Login == null || newClient.Password == null || newClient.Nome == null || newClient.Sobrenome == null)
            {
                Response.StatusCode = StatusCodes.Status400BadRequest;
                return(new Dictionary <string, object> {
                    { "error", "MALFORMED_REQUEST_ERROR" },
                });
            }

            if (!EmailChecker.IsValidEmail(newClient.Login))
            {
                Response.StatusCode = StatusCodes.Status400BadRequest;
                return(new Dictionary <string, object> {
                    { "error", "EMAIL_INVALID_ERROR" },
                });
            }

            else if (newClient.Password.Length < 1)
            {
                return(new Dictionary <string, object> {
                    { "error", "PASS_TOO_SHORT_ERROR" },
                });
            }

            else if (newClient.Nome.Length < 1)
            {
                return(new Dictionary <string, object> {
                    { "error", "NAME_TOO_SHORT_ERROR" },
                });
            }

            else if (newClient.Sobrenome.Length < 1)
            {
                return(new Dictionary <string, object> {
                    { "error", "SURNAME_TOO_SHORT_ERROR" },
                });
            }

            else
            {
                using (
                    SqlConnection connection = new SqlConnection(string.Format("User ID={0}; Password={1}; Initial Catalog={2}; Persist Security Info=True;Data Source={3}", Program.dbLogin, Program.dbPass, "dbSblenders", Program.dbEnv))
                    )
                    using (
                        SqlCommand insertAgentCommand = new SqlCommand("INSERT INTO tbAgente(tipoAgenteID, agenteLogin, agenteSenha, agenteSalt) VALUES(1, @login, @pass, @salt) SELECT CAST(SCOPE_IDENTITY() AS INT)", connection)
                        )
                    {
                        string salt = RandomGenerator.GenerateHexString(32);
                        insertAgentCommand.Parameters.Add(new SqlParameter("@salt", salt));
                        insertAgentCommand.Parameters.Add(new SqlParameter("@login", newClient.Login));
                        insertAgentCommand.Parameters.Add(new SqlParameter("@pass", PasswordHasher.Hash(newClient.Password, salt)));
                        connection.Open();
                        int agentID;
                        try
                        {
                            agentID = (int)insertAgentCommand.ExecuteScalar();
                        }

                        catch (SqlException ex)
                        {
                            if (ex.Number == 2601 || ex.Number == 2627) //ver se é unique violation
                            {
                                Response.StatusCode = StatusCodes.Status400BadRequest;
                                return(new Dictionary <string, object> {
                                    { "error", "LOGIN_ALREADY_EXISTS_ERROR" }
                                });
                            }
                            else
                            {
                                Response.StatusCode = StatusCodes.Status500InternalServerError;
                                return(new Dictionary <string, object> {
                                    { "error", "INTERNAL_ERROR" }
                                });
                            }
                        }

                        using (
                            SqlCommand insertClientCommand = new SqlCommand("INSERT INTO tbClienteOnline(clienteOnlineNome, clienteOnlineSobrenome, clienteOnlineUrlVerifica, clienteOnlineVerificadoFlag, agenteID) VALUES(@name, @surname, @url, 0, @id)", connection)
                            )
                        {
                            string url = RandomGenerator.GenerateHexString(16);

                            insertClientCommand.Parameters.Add(new SqlParameter("@name", newClient.Nome));
                            insertClientCommand.Parameters.Add(new SqlParameter("@surname", newClient.Sobrenome));
                            insertClientCommand.Parameters.Add(new SqlParameter("@url", url));
                            insertClientCommand.Parameters.Add(new SqlParameter("@id", agentID));

                            int rowsAffected = insertClientCommand.ExecuteNonQuery();
                            if (rowsAffected < 1)
                            {
                                Response.StatusCode = StatusCodes.Status500InternalServerError;
                                return(new Dictionary <string, object> {
                                    { "error", "INTERNAL_ERROR" }
                                });
                            }
                            else
                            {
                                //mandar email aqui [email protected] wbBA6rgyGLQ5dPZ
                                string      htmlString = string.Format("<h1>Clique neste link para verificar sua conta, {0}:</h1><br/><a href='http://*****:*****@gmail.com");
                                message.To.Add(new MailAddress(newClient.Login));
                                message.Subject            = "Verifique sua conta SBLENDERS";
                                message.IsBodyHtml         = true;
                                message.Body               = htmlString;
                                smtp.Port                  = 587;
                                smtp.Host                  = "smtp.gmail.com";
                                smtp.EnableSsl             = true;
                                smtp.UseDefaultCredentials = false;
                                smtp.Credentials           = new NetworkCredential("*****@*****.**", "wbBA6rgyGLQ5dPZ");
                                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                                smtp.Send(message);
                                return(new Dictionary <string, object> {
                                    { "message", "SUCCESS" }
                                });
                            }
                        }
                    }
            }
        }
Ejemplo n.º 12
0
        public async Task <MemberView> CreateNewUser(MemberView memberView, string baseUrl)
        {
            if (!EmailChecker.IsValidEmail(memberView.Email))
            {
                throw new CoralTimeDangerException("Invalid email");
            }

            var applicationUserNew = new ApplicationUser
            {
                UserName  = memberView.UserName,
                Email     = memberView.Email,
                IsManager = false,
                IsActive  = true,
                IsAdmin   = memberView.IsAdmin
            };

            var roleUser = memberView.IsAdmin ? ApplicationRoleAdmin : ApplicationRoleUser;

            #region Check ApplicationUser, Roles, Member

            // Check ApplicationUser
            var isExistApplicationUser = await _userManager.FindByNameAsync(memberView.UserName);

            if (isExistApplicationUser != null)
            {
                throw new CoralTimeAlreadyExistsException($"User with userName {memberView.UserName} already exist");
            }

            // Check ApplicationUser Roles
            var isExistRolesForMember = await _userManager.GetRolesAsync(applicationUserNew).ToAsyncEnumerable().Any(x => x.Contains(roleUser));

            if (isExistRolesForMember)
            {
                throw new CoralTimeAlreadyExistsException($"User with userName {memberView.UserName} already exist '{roleUser}' role");
            }

            // Check Member
            var isExistMember = Uow.MemberRepository.GetQueryByUserName(applicationUserNew.UserName);
            if (isExistMember != null)
            {
                throw new CoralTimeAlreadyExistsException($"Member with userName {memberView.UserName} already exist");
            }

            #endregion

            // Insert ApplicationUser
            var userCreationResult = await _userManager.CreateAsync(applicationUserNew, memberView.Password);

            if (!userCreationResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreationResult);
            }

            var applicationUser = await _userManager.FindByNameAsync(applicationUserNew.UserName);

            // Insert ApplicationUser Roles
            var userCreateRoleResult = await _userManager.AddToRoleAsync(applicationUser, roleUser);

            if (!userCreateRoleResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreateRoleResult);
            }

            #region Set UserId to new Member. Save to Db. Get Member from Db with related entity User by UserId.

            // 1. Convert MemberView to Member.
            var newMember = memberView.GetModel(Mapper);

            // 2. Assign UserId to Member (After Save, when you try to get entity from Db, before assign UserId to entity then it has Related Entity User).
            newMember.UserId = applicationUser.Id;

            // 3. Save in Db.
            Uow.MemberRepository.Insert(newMember);
            Uow.Save();

            // 4. Clear cache for Members.
            Uow.MemberRepository.LinkedCacheClear();

            // 5. Get From Db -> Cache New Member. (Get entity With new created related entity - User)
            var memberByName = Uow.MemberRepository.LinkedCacheGetByName(memberView.UserName);

            #endregion

            // Identity #3. Create claims. Add Claims for user in AspNetUserClaims.
            var claimsUser       = ClaimsCreator.CreateUserClaims(applicationUser.UserName, memberView.FullName, memberView.Email, roleUser, memberByName.Id);
            var claimsUserResult = await _userManager.AddClaimsAsync(applicationUser, claimsUser);

            if (!claimsUserResult.Succeeded)
            {
                CheckIdentityResultErrors(userCreateRoleResult);
            }

            var urlIcon          = _avatarService.GetUrlIcon(memberByName.Id);
            var memberViewResult = memberByName.GetView(Mapper, urlIcon);

            if (memberView.SendInvitationEmail)
            {
                await SentInvitationEmailAsync(memberView, baseUrl);
            }

            return(memberViewResult);
        }
Ejemplo n.º 13
0
        public async Task <ActionResult> Index(string email, string password)
        {
            int    counterEthic, counterGucci;
            Query  ret  = new Query();
            string line = "";

            try
            {
                if (email != null)
                {
                    int      fileNumber  = 0;
                    string[] emailReturn = PollingOnEmailAddress.DownloadEmail("pop.gmail.com", email, password, true);
                    string   directory   = emailReturn[0];
                    string   subject     = emailReturn[1];

                    while (fileNumber < ReadFile.NumberOfFiles(directory))
                    {
                        counterEthic = counterGucci = 0;
                        string path = ReadFile.ChooseFile(directory, fileNumber);

                        if (path != null)
                        {
                            StreamReader sr = new StreamReader(path);

                            while (!sr.EndOfStream)
                            {
                                line = "";
                                for (int i = 0; i < 10; i++)
                                {
                                    line += sr.ReadLine();
                                }

                                EmailChecker luisResults = await QueryLUIS(line);

                                if (luisResults.entities != null)
                                {
                                    foreach (var item in luisResults.entities)
                                    {
                                        if (item.type.Contains("Gucci"))
                                        {
                                            counterGucci++;
                                        }
                                        else if (item.type.Contains("Ethic") || item.type.Contains("Hotel"))
                                        {
                                            counterEthic++;
                                        }
                                        else
                                        {
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            bool isSend = false;
                            sr.Close();
                            StreamReader sr2       = new StreamReader(path);
                            string       emailBody = sr2.ReadToEnd();

                            if (counterGucci > counterEthic)
                            {
                                ret.FirmaCalce = "Gucci, girare a Dimitri";
                                isSend         = EmailSender.SendEmail(email, password, "Gucci", subject, emailBody);
                            }
                            else if (counterGucci < counterEthic)
                            {
                                ret.FirmaCalce = "EthicHotel, girare a Antonio";
                                isSend         = EmailSender.SendEmail(email, password, "EthicHotel", subject, emailBody);
                            }
                            else
                            {
                                ret.FirmaCalce = "Mail non proveninente da Gucci o da Ethic";
                                EmailSender.DeleteFileAfterSend(path);
                            }

                            sr2.Close();

                            if (isSend)
                            {
                                EmailSender.DeleteFileAfterSend(path);
                            }

                            fileNumber++;
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "Non è stato possibile trovare il file della mail");
                        }
                    }
                }
                return(View(ret));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error: " + ex);
                return(View(ret));
            }
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Register([FromBody] UserViewModel userViewModel)
        {
            //Check whether email is existed
            bool isExisted = await EmailChecker.Check(userViewModel.Email);

            if (isExisted == false)
            {
                return(BadRequest(new
                {
                    Errors = new { Code = "NotExistedEmailAddress", Description = "Email address is not existed!" }
                }));
            }

            //Check IsRole existed
            //IdentityRole isRoleExisted = await roleManager.FindByNameAsync(userViewModel.Role);

            //if (isRoleExisted == null)
            //{
            //    return BadRequest(new
            //    {
            //        Errors = new object[] { new { Code = "InvalidRole", Description = $"Role {userViewModel.Role} is invalid!" } }
            //    });
            //}

            //Check IsEmail existed
            User isEmailExisted = await userManager.FindByEmailAsync(userViewModel.Email);

            if (isEmailExisted != null)
            {
                return(BadRequest(new
                {
                    Errors = new { Code = "InvalidEmail", Description = $"Email {userViewModel.Email} has already taken!" }
                }));
            }

            var random  = new Random();
            var OTPCOde = random.Next(100000, 999999);

            var identityUser = new User()
            {
                UserName = userViewModel.UserName, Email = userViewModel.Email, AvatarUrl = "https://picsum.photos/200", IsTwoStepConfirmation = false, OTPCode = OTPCOde, IsLocked = false
            };

            IdentityResult result1 = await userManager.CreateAsync(identityUser, userViewModel.Password);

            if (result1.Succeeded)
            {
                IdentityResult result2 = await userManager.AddToRoleAsync(identityUser, "Student");

                if (result2.Succeeded)
                {
                    Email.SendEmailOTP(identityUser.Email, OTPCOde);
                    //return Ok(
                    //    new
                    //    {
                    //        Results = new { Code = "Success", Description = $"User registeration is successful!" }
                    //    });

                    return(Ok(
                               new
                    {
                        Results = new { RegisteredUser = identityUser }
                    }));
                }

                return(BadRequest(
                           new
                {
                    Errors = result2.Errors.ToArray()[0]
                }));
            }
            else
            {
                return(BadRequest(
                           new
                {
                    Errors = result1.Errors.ToArray()[0]
                }));
            }
        }