Example #1
0
        public async Task <AppUserAccessKey> UpdateAccountActivationAccessKey(string baseAddress, long id)
        {
            if (baseAddress == null)
            {
                throw new ArgumentNullException(nameof(baseAddress));
            }
            AppUserAccessKey accessKeys = new AppUserAccessKey();

            try
            {
                using (var httpClient = new HttpClient())
                {
                    // Do the actual request and await the response
                    baseAddress = baseAddress + id;
                    var httpResponse = await httpClient.GetAsync(baseAddress);

                    if (httpResponse != null)
                    {
                        if (httpResponse.IsSuccessStatusCode)
                        {
                            var stringData = httpResponse.Content.ReadAsStringAsync().Result;
                            accessKeys = await Task.Run(() => JsonConvert.DeserializeObject <AppUserAccessKey>(stringData));
                        }
                    }
                }
                return(accessKeys);
            }
            catch (Exception)
            {
                return(accessKeys);
            }
        }
Example #2
0
        public void SendNewUserEmail(string path, AppUser appUser, AppUserAccessKey accessKey)
        {
            try
            {
                //From Address
                var fromAddress     = "*****@*****.**";
                var fromAdressTitle = "Afriplugz";
                //To Address
                var toVendor = appUser.Email;
                //var toCustomer = email;
                var toAdressTitle = appUser.Name;
                var subject       = "Afriplugz (Activate Account).";

                //Smtp Server
                var smtpServer = new AppConfig().EmailServer;
                //Smtp Port Number
                var smtpPortNumber = new AppConfig().Port;

                var mimeMessageVendor = new MimeMessage();
                mimeMessageVendor.From.Add(new MailboxAddress(fromAdressTitle, fromAddress));
                mimeMessageVendor.To.Add(new MailboxAddress(toAdressTitle, toVendor));
                mimeMessageVendor.Subject = subject;
                var bodyBuilder = new BodyBuilder();
                using (var data = File.OpenText(path))
                {
                    {
                        //manage content

                        bodyBuilder.HtmlBody = data.ReadToEnd();
                        var body = bodyBuilder.HtmlBody;

                        var replace = body.Replace("USER", appUser.Name);
                        replace = replace.Replace("URL", new AppConfig().AppUrl + "Account/AccountActivationLink?accessCode=" +
                                                  accessKey.AccountActivationAccessCode);
                        replace = replace.Replace("LOGO", new AppConfig().AppLogo);
                        replace = replace.Replace("APPURL", new AppConfig().AppUrl);
                        replace = replace.Replace("TC", new AppConfig().Terms);
                        replace = replace.Replace("PRIVACY", new AppConfig().PrivacyPolicy);
                        bodyBuilder.HtmlBody   = replace;
                        mimeMessageVendor.Body = bodyBuilder.ToMessageBody();
                    }
                }

                using (var client = new SmtpClient())
                {
                    client.Connect(smtpServer, smtpPortNumber);
                    // Note: only needed if the SMTP server requires authentication
                    // Error 5.5.1 Authentication
                    client.Authenticate(new AppConfig().SupportEmail, new AppConfig().SupportEmailPassword);
                    client.Send(mimeMessageVendor);
                    client.Disconnect(true);
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
Example #3
0
        public bool SendNewUserEmail(string path, AppUser appUser, string role, AppUserAccessKey accessKey)
        {
            bool success = false;
            //From Address
            var FromAddress     = "*****@*****.**";
            var FromAdressTitle = "Camerack Studio";
            //To Address
            var toVendor = appUser.Email;
            //var toCustomer = email;
            var ToAdressTitle = "Camerack Studio";
            var Subject       = "Activate Account.";
            //var BodyContent = message;

            //Smtp Server
            var smtpServer = new AppConfig().EmailServer;
            //Smtp Port Number
            var smtpPortNumber = new AppConfig().Port;

            var mimeMessageVendor = new MimeMessage();

            mimeMessageVendor.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
            mimeMessageVendor.To.Add(new MailboxAddress(ToAdressTitle, toVendor));
            mimeMessageVendor.Subject = Subject;
            BodyBuilder bodyBuilder = new BodyBuilder();

            using (var data = File.OpenText(path))
            {
                if (data.BaseStream != null)
                {
                    //manage content

                    bodyBuilder.HtmlBody = data.ReadToEnd();
                    var body = bodyBuilder.HtmlBody;

                    var replace = body.Replace("NAME", appUser.Name);
                    replace = replace.Replace("URL", new AppConfig().MarketPlaceBaseUrl + "Account/AccountActivationLink?accessCode=" + accessKey.AccountActivationAccessCode);
                    replace = replace.Replace("ROLE", role);
                    replace = replace.Replace("DATE", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    bodyBuilder.HtmlBody   = replace;
                    mimeMessageVendor.Body = bodyBuilder.ToMessageBody();
                }
            }
            using (var client = new SmtpClient())
            {
                client.Connect(smtpServer, smtpPortNumber);
                // Note: only needed if the SMTP server requires authentication
                // Error 5.5.1 Authentication
                client.Authenticate(new AppConfig().Email, new AppConfig().Password);
                client.Send(mimeMessageVendor);
                if (client.IsConnected)
                {
                    success = true;
                }
                client.Disconnect(true);
            }
            return(success);
        }
Example #4
0
        public void SendForgotPasswordResetLink(string path, AppUser appUser, AppUserAccessKey accessKey)
        {
            //From Address
            var fromAddress     = "*****@*****.**";
            var fromAdressTitle = "Afriplugz";
            //To Address
            var toVendor = appUser.Email;
            //var toCustomer = email;
            var toAdressTitle = appUser.Name;
            var subject       = "Afriplugz (Password Reset).";

            //Smtp Server
            var smtpServer = new AppConfig().EmailServer;
            //Smtp Port Number
            var smtpPortNumber = new AppConfig().Port;

            var mimeMessageVendor = new MimeMessage();

            mimeMessageVendor.From.Add(new MailboxAddress(fromAdressTitle, fromAddress));
            mimeMessageVendor.To.Add(new MailboxAddress(toAdressTitle, toVendor));
            mimeMessageVendor.Subject = subject;
            var bodyBuilder = new BodyBuilder();

            using (var data = File.OpenText(path))
            {
                {
                    //manage content

                    bodyBuilder.HtmlBody = data.ReadToEnd();
                    var body = bodyBuilder.HtmlBody;

                    var replace = body.Replace("USER", appUser.Name);
                    replace = replace.Replace("DATE", DateTime.Now.ToString(CultureInfo.InvariantCulture));

                    replace = replace.Replace("URL", new AppConfig().AppUrl +
                                              "Account/ForgotPassword?accessCode=" +
                                              accessKey.PasswordAccessCode);
                    replace = replace.Replace("LOGO", new AppConfig().AppLogo);
                    replace = replace.Replace("APPURL", new AppConfig().AppUrl);
                    replace = replace.Replace("TC", new AppConfig().Terms);
                    replace = replace.Replace("PRIVACY", new AppConfig().PrivacyPolicy);
                    bodyBuilder.HtmlBody   = replace;
                    mimeMessageVendor.Body = bodyBuilder.ToMessageBody();
                }
            }

            using (var client = new SmtpClient())
            {
                client.Connect(smtpServer, smtpPortNumber, true);
                // Note: only needed if the SMTP server requires authentication
                // Error 5.5.1 Authentication
                client.Authenticate(new AppConfig().SupportEmail, new AppConfig().SupportEmailPassword);
                client.Send(mimeMessageVendor);
                client.Disconnect(true);
            }
        }
Example #5
0
        public void SendForgotPasswordResetLink(string path, AppUser appUser, AppUserAccessKey accessKey)
        {
            //From Address
            var FromAddress     = "*****@*****.**";
            var FromAdressTitle = "Camerack Studio";
            //To Address
            var toVendor = appUser.Email;
            //var toCustomer = email;
            var ToAdressTitle = "Camerack Studio";
            var Subject       = "Password Reset.";
            //var BodyContent = message;

            //Smtp Server
            var smtpServer = new AppConfig().EmailServer;
            //Smtp Port Number
            var smtpPortNumber = new AppConfig().Port;

            var mimeMessageVendor = new MimeMessage();

            mimeMessageVendor.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
            mimeMessageVendor.To.Add(new MailboxAddress(ToAdressTitle, toVendor));
            mimeMessageVendor.Subject = Subject;
            BodyBuilder bodyBuilder = new BodyBuilder();

            using (StreamReader data = File.OpenText(path))
            {
                if (data.BaseStream != null)
                {
                    //manage content

                    bodyBuilder.HtmlBody = data.ReadToEnd();
                    var body = bodyBuilder.HtmlBody;

                    var replace = body.Replace("NAME", appUser.Name);
                    replace = replace.Replace("DATE", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    replace = replace.Replace("URL", "http://studio.camerack.com/Account/ForgotPassword?accessCode=" + accessKey.PasswordAccessCode);
                    bodyBuilder.HtmlBody   = replace;
                    mimeMessageVendor.Body = bodyBuilder.ToMessageBody();
                }
            }
            using (var client = new MailKit.Net.Smtp.SmtpClient())
            {
                client.Connect(smtpServer, smtpPortNumber, true);
                // Note: only needed if the SMTP server requires authentication
                // Error 5.5.1 Authentication
                client.Authenticate(new AppConfig().Email, new AppConfig().Password);
                client.Send(mimeMessageVendor);
                client.Disconnect(true);
            }
        }
        public ActionResult Login(AccountModel model)
        {
            var access    = new AccessLog();
            var email     = model.Email.ToLower();
            var userExist = _databaseConnection.AppUsers
                            .Include(n => n.Role).SingleOrDefault(
                n => n.Email.ToLower() == email);

            try
            {
                if (model.LoginType != LoginType.Google.ToString() &&
                    model.LoginType != LoginType.Facebook.ToString() &&
                    model.LoginType != LoginType.Twitter.ToString())
                {
                    model.LoginType = LoginType.Platform.ToString();

                    //for platform login
                    if (model.LoginType == LoginType.Platform.ToString())
                    {
                        if (userExist == null)
                        {
                            access.Message          = "Your Email/Password is Incorrect. Try again!";
                            access.Status           = AccessStatus.Denied.ToString();
                            access.Category         = AccessCategory.Login.ToString();
                            access.DateCreated      = DateTime.Now;
                            access.DateLastModified = DateTime.Now;
                            access.AppUser          = null;
                            _databaseConnection.AccessLogs.Add(access);
                            _databaseConnection.SaveChanges();
                        }
                        else
                        {
                            if (userExist.HasSocialMediaLogin == false)
                            {
                                if (userExist.Status == UserStatus.Inactive.ToString())
                                {
                                    access.Message =
                                        "You are yet to activate your account from the the link sent to your email when you created the account!";
                                    access.Status           = AccessStatus.Denied.ToString();
                                    access.Category         = AccessCategory.Login.ToString();
                                    access.DateCreated      = DateTime.Now;
                                    access.DateLastModified = DateTime.Now;
                                    access.CreatedBy        = userExist.AppUserId;
                                    access.LastModifiedBy   = userExist.AppUserId;
                                    access.AppUser          = null;
                                    _databaseConnection.AccessLogs.Add(access);
                                    _databaseConnection.SaveChanges();
                                    userExist = null;
                                }

                                var passwordCorrect = userExist != null &&
                                                      new Hashing().ValidatePassword(model.Password,
                                                                                     userExist.ConfirmPassword);
                                if (passwordCorrect == false)
                                {
                                    if (userExist != null)
                                    {
                                        access.Message          = "Your Email/Password is Incorrect. Try again!";
                                        access.Status           = AccessStatus.Denied.ToString();
                                        access.Category         = AccessCategory.Login.ToString();
                                        access.DateCreated      = DateTime.Now;
                                        access.DateLastModified = DateTime.Now;
                                        access.CreatedBy        = userExist.AppUserId;
                                        access.AppUser          = null;
                                        access.LastModifiedBy   = userExist.AppUserId;
                                        _databaseConnection.AccessLogs.Add(access);
                                        _databaseConnection.SaveChanges();
                                        userExist = null;
                                    }
                                }

                                if (passwordCorrect)
                                {
                                    access.Message          = "Dear " + userExist.Name + ", You have successfully logged in!";
                                    access.Status           = AccessStatus.Approved.ToString();
                                    access.Category         = AccessCategory.Login.ToString();
                                    access.DateCreated      = DateTime.Now;
                                    access.AppUserId        = userExist.AppUserId;
                                    access.DateLastModified = DateTime.Now;
                                    access.CreatedBy        = userExist.AppUserId;
                                    access.LastModifiedBy   = userExist.AppUserId;

                                    _databaseConnection.AccessLogs.Add(access);
                                    _databaseConnection.SaveChanges();
                                }
                            }
                            else
                            {
                                access.Message =
                                    "Your Email/Password is Incorrect. Try again!";
                                access.Status           = AccessStatus.Denied.ToString();
                                access.Category         = AccessCategory.Login.ToString();
                                access.DateCreated      = DateTime.Now;
                                access.DateLastModified = DateTime.Now;
                                access.CreatedBy        = null;
                                access.LastModifiedBy   = null;
                                access.AppUser          = null;
                                _databaseConnection.AccessLogs.Add(access);
                                _databaseConnection.SaveChanges();
                                userExist = null;
                            }
                        }
                    }
                }

                //for social media login
                if (model.LoginType != LoginType.Platform.ToString())
                {
                    if (userExist == null)
                    {
                        var appUser = new AppUser
                        {
                            Name                = model.UserName,
                            Mobile              = "N/A",
                            Email               = model.Email,
                            Status              = UserStatus.Active.ToString(),
                            Address             = "N/A",
                            ProfilePicture      = model.ProfilePicture,
                            RoleId              = _databaseConnection.AppCredentials.FirstOrDefault()?.CustomerId,
                            DateCreated         = DateTime.Now,
                            DateLastModified    = DateTime.Now,
                            CreatedBy           = null,
                            LastModifiedBy      = null,
                            HasSocialMediaLogin = true,
                            AccountType         = model.LoginType
                        };
                        if (string.IsNullOrEmpty(appUser.Password))
                        {
                            appUser.Password        = new Hashing().HashPassword(new Md5Ecryption().RandomString(5));
                            appUser.ConfirmPassword = appUser.Password;
                        }

                        _databaseConnection.AppUsers.Add(appUser);
                        _databaseConnection.SaveChanges();
                        if (appUser.AppUserId > 0)
                        {
                            //define acceskeys and save transactions
                            var accessKey = new AppUserAccessKey
                            {
                                PasswordAccessCode          = new Md5Ecryption().RandomString(15),
                                AccountActivationAccessCode = new Md5Ecryption().RandomString(20),
                                CreatedBy        = appUser.AppUserId,
                                LastModifiedBy   = appUser.AppUserId,
                                DateCreated      = DateTime.Now,
                                DateLastModified = DateTime.Now,
                                ExpiryDate       = DateTime.Now.AddDays(1),
                                AppUserId        = appUser.AppUserId
                            };
                            _databaseConnection.AppUserAccessKeys.Add(accessKey);
                            _databaseConnection.SaveChanges();
                            access.Message          = "You have successfully logged in!";
                            access.Status           = AccessStatus.Approved.ToString();
                            access.Category         = AccessCategory.Login.ToString();
                            access.DateCreated      = DateTime.Now;
                            access.DateLastModified = DateTime.Now;
                            access.AppUser          = null;
                            _databaseConnection.AccessLogs.Add(access);
                            _databaseConnection.SaveChanges();
                            //create and populate user transport object
                            new Mailer().SendNewUserSocialEmail(new AppConfig().NewUserSocialHtml, appUser);
                            userExist = _databaseConnection.AppUsers
                                        .Include(n => n.Role).SingleOrDefault(n => n.AppUserId == appUser.AppUserId);
                        }
                    }
                    else
                    {
                        userExist.ProfilePicture   = model.ProfilePicture;
                        userExist.DateLastModified = DateTime.Now;
                        //update user
                        _databaseConnection.Entry(userExist).State = EntityState.Modified;
                        _databaseConnection.SaveChanges();

                        access.Message          = "Dear " + userExist.Name + " You have successfully logged in!";
                        access.Status           = AccessStatus.Approved.ToString();
                        access.Category         = AccessCategory.Login.ToString();
                        access.DateCreated      = DateTime.Now;
                        access.DateLastModified = DateTime.Now;
                        access.AppUser          = null;
                        access.AppUserId        = userExist.AppUserId;
                        _databaseConnection.AccessLogs.Add(access);
                        _databaseConnection.SaveChanges();
                    }
                }

                HttpContext.Session.SetString("FrscQuestionLoggedInUser", JsonConvert.SerializeObject(userExist));
                if (userExist != null)
                {
                    HttpContext.Session.SetString("FrscQuestionLoggedInUserId", userExist.AppUserId.ToString());
                }
                if (userExist != null)
                {
                    var role = _databaseConnection.Roles.Find(userExist.RoleId);
                    if (role.AccessAdminConsole && role.ManageApplicationUser)
                    {
                        return(RedirectToAction("Dashboard", "User"));
                    }

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

                //display notification
                TempData["display"]          = access.Message;
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View(model));
            }
            catch (Exception)
            {
                //display notification
                TempData["display"]          = "Unable to Sign In. Try again!";
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View(model));
            }
        }
        public ActionResult Register(AccountModel model)
        {
            var access    = new AccessLog();
            var email     = model.Email.ToLower();
            var userExist = _databaseConnection.AppUsers.Include(n => n.Role).SingleOrDefault(
                n => n.Email.ToLower() == email);
            var hashPassword = new Hashing().HashPassword(model.Password);

            try
            {
                var appUser = new AppUser
                {
                    Name           = model.LoginName,
                    Mobile         = model.Mobile,
                    Email          = model.Email,
                    Status         = UserStatus.Inactive.ToString(),
                    ProfilePicture =
                        "../images/avatar.png",
                    DateCreated         = DateTime.Now,
                    DateLastModified    = DateTime.Now,
                    RoleId              = _databaseConnection.AppCredentials.FirstOrDefault()?.EventPlannerId,
                    Password            = hashPassword,
                    ConfirmPassword     = hashPassword,
                    Address             = "N/A",
                    AccountType         = LoginType.Platform.ToString(),
                    HasSocialMediaLogin = false
                };

                //invalid user because the user email exists
                if (userExist != null)
                {
                    access.Message          = "A user with the same Email already exist, try another Credential!";
                    access.Status           = AccessStatus.Denied.ToString();
                    access.Category         = AccessCategory.Registration.ToString();
                    access.DateCreated      = DateTime.Now;
                    access.DateLastModified = DateTime.Now;
                    _databaseConnection.AccessLogs.Add(access);
                    _databaseConnection.SaveChanges();
                    //display notification
                    TempData["display"]          = access.Message;
                    TempData["notificationtype"] = NotificationType.Error.ToString();
                    return(View("Register", model));
                }
                //valid user

                _databaseConnection.AppUsers.Add(appUser);
                _databaseConnection.SaveChanges();
                //define acceskeys and save transactions
                var accessKey = new AppUserAccessKey
                {
                    PasswordAccessCode          = new Md5Ecryption().RandomString(15),
                    AccountActivationAccessCode = new Md5Ecryption().RandomString(20),
                    CreatedBy        = appUser.AppUserId,
                    LastModifiedBy   = appUser.AppUserId,
                    DateCreated      = DateTime.Now,
                    DateLastModified = DateTime.Now,
                    ExpiryDate       = DateTime.Now.AddDays(1),
                    AppUserId        = appUser.AppUserId
                };
                _databaseConnection.AppUserAccessKeys.Add(accessKey);
                _databaseConnection.SaveChanges();

                //determine access logs save transaction
                access.Message =
                    "You have successfully registered, Check your email to confirm your account!";
                access.Status           = AccessStatus.Approved.ToString();
                access.Category         = AccessCategory.Registration.ToString();
                access.DateCreated      = DateTime.Now;
                access.DateLastModified = DateTime.Now;
                access.AppUserId        = appUser.AppUserId;
                _databaseConnection.AccessLogs.Add(access);
                _databaseConnection.SaveChanges();


                if (_databaseConnection.Subscriptions.Where(n =>
                                                            n.Email == appUser.Email).ToList()
                    .Count <= 0)
                {
                    if (appUser.AppUserId > 0)
                    {
                        var subscription = new Subscription
                        {
                            Email            = appUser.Email,
                            Name             = appUser.Name,
                            Status           = "Active",
                            DateCreated      = DateTime.Now,
                            DateLastModified = DateTime.Now,
                            CreatedBy        = appUser.AppUserId,
                            LastModifiedBy   = appUser.AppUserId
                        };
                        _databaseConnection.Add(subscription);
                    }

                    _databaseConnection.SaveChanges();
                }
                //create and populate user transport object
                new Mailer().SendNewUserEmail(new AppConfig().NewUserHtml, appUser, accessKey);


                //display notification
                if (appUser.AppUserId > 0)
                {
                    TempData["display"] =
                        access.Message;
                    TempData["notificationtype"] = NotificationType.Success.ToString();
                }

                return(RedirectToAction("Login"));
            }
            catch (Exception ex)
            {
                //display notification
                TempData["display"]          = ex.ToString();
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View("Register", model));
            }
        }
        public ActionResult Register([FromBody] AppUser model)
        {
            try
            {
                var username = model.Username.ToLower();
                var email    = model.Email.ToLower();
                var appUser  = new AppUser
                {
                    Name                = model.Name,
                    Mobile              = model.Mobile,
                    Email               = model.Email,
                    MobileExtension     = null,
                    Password            = new Hashing().HashPassword(model.ConfirmPassword),
                    ConfirmPassword     = new Hashing().HashPassword(model.ConfirmPassword),
                    Username            = model.Username,
                    Status              = model.Status,
                    Address             = model.Address,
                    BackgroundPicture   = model.BackgroundPicture,
                    ProfilePicture      = model.ProfilePicture,
                    Biography           = model.Biography,
                    DateOfBirth         = model.DateOfBirth,
                    Website             = model.Website,
                    RoleId              = model.RoleId,
                    DateCreated         = DateTime.Now,
                    DateLastModified    = DateTime.Now,
                    CreatedBy           = model.CreatedBy,
                    LastModifiedBy      = model.LastModifiedBy,
                    HasSocialMediaLogin = false,
                    AccountType         = LoginType.Platform.ToString()
                };
                //invalid user becuase the user username exists
                if (_databaseConnection.AppUsers.Any(n => n.Username.ToLower() == username &&
                                                     n.HasSocialMediaLogin == false))
                {
                    ViewBag["display"]  = NotificationType.Error.ToString();
                    ViewData["Message"] =
                        "A user with the same Username already exist, try another Credential!";
                    return(View(model));
                }
                if (_databaseConnection.AppUsers.Any(
                        n => n.Username.ToLower() == username && n.HasSocialMediaLogin))
                {
                    ViewBag["display"]  = NotificationType.Error.ToString();
                    ViewData["Message"] =
                        "A user with the same Username already exist via Social Media Login, try another Credential!";
                    return(View(model));
                }
                //invalid user becuase the user email exists
                if (_databaseConnection.AppUsers.Any(
                        n => n.Email.ToLower() == email && n.HasSocialMediaLogin == false))
                {
                    ViewBag["display"]  = NotificationType.Error.ToString();
                    ViewData["Message"] = "A user with the same Email already exist, try another Credential!";
                    return(View(model));
                }
                if (_databaseConnection.AppUsers.Any(
                        n => n.Email.ToLower() == email && n.HasSocialMediaLogin))
                {
                    ViewBag["display"]  = NotificationType.Error.ToString();
                    ViewData["Message"] =
                        "A user with the same Email already exist via Social Media Login, try another Credential!";
                    return(View(model));
                }
                //valid user
                _databaseConnection.AppUsers.Add(appUser);
                _databaseConnection.SaveChanges();
                appUser.Role = _databaseConnection.Roles.Find(appUser.RoleId);

                //define acceskeys and save transactions
                var accessKey = new AppUserAccessKey
                {
                    PasswordAccessCode          = new Md5Ecryption().RandomString(15),
                    AccountActivationAccessCode = new Md5Ecryption().RandomString(20),
                    CreatedBy        = appUser.AppUserId,
                    LastModifiedBy   = appUser.AppUserId,
                    DateCreated      = DateTime.Now,
                    DateLastModified = DateTime.Now,
                    ExpiryDate       = DateTime.Now.AddDays(1),
                    AppUserId        = appUser.AppUserId
                };
                _databaseConnection.AppUserAccessKeys.Add(accessKey);
                _databaseConnection.SaveChanges();

                //determine access logs save transaction
                ViewData["Message"] = "You have successfully registered, Check your email to confirm your account!";
                ViewBag["display"]  = NotificationType.Success.ToString();
                //new SendEmailMessage().SendNewUserEmailMessage(userTransport);

                return(View(appUser));
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "Request is unavailable at the moment, Try again Later!";
                ViewBag["display"]  = NotificationType.Error.ToString();
                return(View(model));
            }
        }
        public ActionResult Login([FromBody] AccountModel model)
        {
            var     access    = new AccessLog();
            AppUser userExist = null;

            try
            {
                //for platform login
                if (model != null && model.LoginType == LoginType.Platform.ToString())
                {
                    var loginName = model.LoginName.ToLower();
                    userExist = _databaseConnection.AppUsers.Include(n => n.Role).SingleOrDefault(
                        n => n.Email.ToLower() == loginName || n.Username == loginName);
                    if (userExist == null)
                    {
                        ViewData["Message"] = "The Account does not exist,Check and Try again!";
                        ViewBag["display"]  = NotificationType.Error.ToString();
                    }
                    else
                    {
                        if (userExist.HasSocialMediaLogin == false)
                        {
                            if (userExist.Status == UserStatus.Inactive.ToString())
                            {
                                ViewData["Message"] =
                                    "You are yet to activate your account from the the link sent to your " +
                                    "email when you created the account!";
                                ViewBag["display"] = NotificationType.Error.ToString();
                                return(View(model));
                            }


                            var passwordCorrect = userExist != null &&
                                                  new Hashing().ValidatePassword(model.Password,
                                                                                 userExist.ConfirmPassword);
                            if (passwordCorrect == false)
                            {
                                if (userExist != null)
                                {
                                    ViewData["Message"] = "Dear " + userExist.Name +
                                                          " your Password is Incorrect, Check and Try again!";
                                    ViewBag["display"] = NotificationType.Error.ToString();
                                    return(View(model));
                                }
                            }
                            if (passwordCorrect)
                            {
                                ViewData["Message"] = "Dear " + userExist.Name + ", You have successfully logged in!";
                                ViewBag["display"]  = NotificationType.Error.ToString();
                                return(View(model));
                            }
                        }
                        else
                        {
                            ViewData["Message"] =
                                "This Account is Social Media Enabled, Use the Appropriate social Media to Sign In!";
                            ViewBag["display"] = NotificationType.Error.ToString();
                            return(View(model));
                        }
                    }
                }
                else
                {
                    var loginName = model.LoginName.ToLower();
                    userExist = _databaseConnection.AppUsers.Include(n => n.Role).SingleOrDefault(
                        n => n.Email.ToLower() == loginName || n.Username == loginName);


                    if (userExist == null)
                    {
                        var appUser = new AppUser
                        {
                            Name                = model.LoginName,
                            Mobile              = model.Mobile,
                            Email               = model.Email,
                            Username            = model.Username,
                            Status              = UserStatus.Active.ToString(),
                            Address             = "Social Media",
                            BackgroundPicture   = "photo1.jpg",
                            ProfilePicture      = model.ProfilePicture,
                            Biography           = "Social Media",
                            DateOfBirth         = null,
                            Website             = "Social Media",
                            RoleId              = model.RoleId,
                            DateCreated         = DateTime.Now,
                            DateLastModified    = DateTime.Now,
                            CreatedBy           = null,
                            LastModifiedBy      = null,
                            HasSocialMediaLogin = true,
                            AccountType         = model.LoginType,
                            Role                = _databaseConnection.Roles.Find(model.RoleId)
                        };
                        if (string.IsNullOrEmpty(appUser.Password))
                        {
                            appUser.Password        = new Hashing().HashPassword(new Md5Ecryption().RandomString(5));
                            appUser.ConfirmPassword = appUser.Password;
                        }

                        _databaseConnection.AppUsers.Add(appUser);
                        _databaseConnection.SaveChanges();
                        if (appUser.AppUserId > 0)
                        {
                            //define acceskeys and save transactions
                            var accessKey = new AppUserAccessKey
                            {
                                PasswordAccessCode          = new Md5Ecryption().RandomString(15),
                                AccountActivationAccessCode = new Md5Ecryption().RandomString(20),
                                CreatedBy        = appUser.AppUserId,
                                LastModifiedBy   = appUser.AppUserId,
                                DateCreated      = DateTime.Now,
                                DateLastModified = DateTime.Now,
                                ExpiryDate       = DateTime.Now.AddDays(1),
                                AppUserId        = appUser.AppUserId
                            };
                            _databaseConnection.AppUserAccessKeys.Add(accessKey);
                            _databaseConnection.SaveChanges();
                            //create and populate user transport object
                            // new SendEmailMessage().SendNewUserSoialEmailMessage(appUser);
                            return(View(model));
                        }
                    }
                    else
                    {
                        if (!userExist.HasSocialMediaLogin)
                        {
                            ViewData["Message"] =
                                "This Account is a Platform Enabled Account, Use your correct username and password to sign in!";
                            ViewBag["display"] = NotificationType.Error.ToString();
                            return(View(model));
                        }
                        userExist.ProfilePicture = model.ProfilePicture;

                        //update user
                        _databaseConnection.Entry(userExist).State = EntityState.Modified;
                        _databaseConnection.SaveChanges();

                        access.Message     = "Dear " + userExist.Name + " You have successfully logged in!";
                        ViewBag["display"] = NotificationType.Error.ToString();
                        return(View(model));
                    }
                    return(View(model));
                }
                return(View(model));
            }

            catch (Exception ex)
            {
                ViewData["Message"] = "Request Unavailable, Try again later!";
                ViewBag["display"]  = NotificationType.Error.ToString();
                return(View(model));
            }
        }
Example #10
0
        public async Task <IActionResult> AddEmployee(PreEmployee preEmployee)
        {
            var userId       = _session.GetInt32("loggedinusersessionid");
            var restaurantid = _session.GetInt32("restaurantsessionid");
            var restaurant   = _db.Restaurants.Find(restaurantid);

            try
            {
                if (_db.EmployeePersonalDatas.Any(n => n.Email == preEmployee.Email) == false &&
                    _db.AppUsers.Any(n => n.Email == preEmployee.Email) == false)
                {
                    var _employee = new Employee
                    {
                        RestaurantId     = Convert.ToInt32(restaurantid),
                        CreatedBy        = userId,
                        LastModifiedBy   = Convert.ToInt32(userId),
                        DateCreated      = DateTime.Now,
                        DateLastModified = DateTime.Now
                    };

                    _db.Employees.Add(_employee);
                    await _db.SaveChangesAsync();

                    if (_employee.EmployeeId > 0)
                    {
                        //Popluate the personal data object
                        var _employeePersonalData = new EmployeePersonalData
                        {
                            RestaurantId     = Convert.ToInt32(restaurantid),
                            CreatedBy        = userId,
                            LastModifiedBy   = Convert.ToInt32(userId),
                            DateCreated      = DateTime.Now,
                            DateLastModified = DateTime.Now,
                            FirstName        = preEmployee.Firstname,
                            LastName         = preEmployee.Lastname,
                            Email            = preEmployee.Email,
                            PrimaryAddress   = preEmployee.PrimaryAddress,
                            SecondaryAddress = "N/A",
                            State            = "N/A",
                            MiddleName       = "N/A",
                            LGA           = "N/A",
                            HomePhone     = preEmployee.HomePhoneNumber,
                            WorkPhone     = "N/A",
                            DOB           = DateTime.Now,
                            Title         = 0.ToString(),
                            MaritalStatus = 0.ToString(),
                            Gender        = 0.ToString(),
                            POB           = "N/A",
                            EmployeeId    = _employee.EmployeeId
                        };

                        _db.EmployeePersonalDatas.Add(_employeePersonalData);
                        await _db.SaveChangesAsync();

                        var password = new Md5Encryption().RandomString(7);
                        var _appUser = new AppUser
                        {
                            EmployeeId       = _employee.EmployeeId,
                            Email            = _employeePersonalData.Email,
                            Name             = _employeePersonalData.DisplayName,
                            RestaurantId     = Convert.ToInt32(restaurantid),
                            CreatedBy        = userId,
                            LastModifiedBy   = Convert.ToInt32(userId),
                            DateCreated      = DateTime.Now,
                            DateLastModified = DateTime.Now,
                            Password         = new Hashing().HashPassword(password),
                            ConfirmPassword  = new Hashing().HashPassword(password),
                            Status           = UserStatus.Inactive.ToString()
                        };

                        _db.AppUsers.Add(_appUser);
                        await _db.SaveChangesAsync();

                        if (_appUser.AppUserId > 0)
                        {
                            //define acceskeys and save transactions
                            var accesskey = new AppUserAccessKey
                            {
                                PasswordAccessCode          = new Md5Encryption().RandomString(15),
                                AccountActivationAccessCode = new Md5Encryption().RandomString(20),
                                CreatedBy        = _appUser.AppUserId,
                                LastModifiedBy   = _appUser.AppUserId,
                                DateCreated      = DateTime.Now,
                                DateLastModified = DateTime.Now,
                                ExpiryDate       = DateTime.Now.AddDays(1),
                                AppUserId        = _appUser.AppUserId
                            };

                            _db.AppUserAccessKeys.Add(accesskey);
                            await _db.SaveChangesAsync();

                            //new Mailer()
                        }

                        TempData["display"]          = "You have successfully added a new employee!";
                        TempData["notificationType"] = NotificationType.Success.ToString();
                        return(View());
                    }

                    TempData["display"]          = "There is an error performing this action. Try again!";
                    TempData["notificationType"] = NotificationType.Error.ToString();
                    return(View(preEmployee));
                }

                TempData["display"]          = "The employee already exist, try a different email!";
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View(preEmployee));
            }
            catch (Exception ex)
            {
                TempData["display"]          = ex.Message;
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View());
            }
        }
Example #11
0
        public async Task <IActionResult> Create(AppUser appUser)
        {
            try
            {
                //var userid = _session.GetInt32("loggedinuserid");
                var restaurantid = _session.GetInt32("restaurantsessionid");
                var role         = _db.Roles.Find(appUser.Role);
                appUser.RestaurantId = Convert.ToInt32(restaurantid);
                //appUser.CreatedBy = userid;
                //appUser.LastModifiedBy = userid;
                appUser.DateCreated      = DateTime.Now;
                appUser.DateLastModified = DateTime.Now;

                //Generate Password
                var generator = new Random();
                var number    = generator.Next(0, 1000000).ToString("D6");

                appUser.Password        = new Hashing().HashPassword(number);
                appUser.ConfirmPassword = appUser.Password;

                if (_db.AppUsers.Where(au => au.Email == appUser.Email).ToList().Count > 0)
                {
                    TempData["appuser"]          = "******";
                    TempData["notificationtype"] = NotificationType.Error.ToString();
                    return(View(appUser));
                }


                _db.AppUsers.Add(appUser);
                await _db.SaveChangesAsync();

                if (appUser.AppUserId > 0)
                {
                    //define acceskeys and save transactions
                    var accessKey = new AppUserAccessKey
                    {
                        PasswordAccessCode          = new Md5Encryption().RandomString(15),
                        AccountActivationAccessCode = new Md5Encryption().RandomString(20),
                        CreatedBy        = appUser.AppUserId,
                        LastModifiedBy   = appUser.AppUserId,
                        DateCreated      = DateTime.Now,
                        DateLastModified = DateTime.Now,
                        ExpiryDate       = DateTime.Now.AddDays(1),
                        AppUserId        = appUser.AppUserId
                    };

                    _db.AppUserAccessKeys.Add(accessKey);
                    await _db.SaveChangesAsync();

                    //new Mailer().SendNewUserEmail("", appUser, role, accessKey);
                }
                TempData["appuser"]          = "******";
                TempData["notificationtype"] = NotificationType.Success.ToString();
                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                //display notification
                TempData["appuser"]          = ex.Message;
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View(appUser));
            }
        }
        public IActionResult Create(AppUser appUser, IFormFile ProfilePicture)
        {
            var authorizedUser = new AppUser();

            if (HttpContext.Session.GetString("FrscQuestionLoggedInUser") != null)
            {
                var userString = HttpContext.Session.GetString("FrscQuestionLoggedInUser");
                authorizedUser = JsonConvert.DeserializeObject <AppUser>(userString);
            }

            if (!authorizedUser.Role.AccessAdminConsole ||
                !authorizedUser.Role.ManageApplicationUser)
            {
                return(RedirectToAction("UnauthorizedAccess", "Home"));
            }

            try
            {
                var signedInUserId = Convert.ToInt64(HttpContext.Session.GetString("FrscQuestionLoggedInUserId"));
                appUser.CreatedBy           = signedInUserId;
                appUser.LastModifiedBy      = signedInUserId;
                appUser.DateCreated         = DateTime.Now;
                appUser.DateLastModified    = DateTime.Now;
                appUser.HasSocialMediaLogin = false;
                appUser.Status              = UserStatus.Inactive.ToString();
                appUser.AccountType         = LoginType.Platform.ToString();
                appUser.HasSocialMediaLogin = false;
                //generate password
                var password = new Md5Ecryption().RandomString(8);

                appUser.Password        = new Hashing().HashPassword(password);
                appUser.ConfirmPassword = appUser.Password;

                if (_databaseConnection.AppUsers.Where(n => n.Email == appUser.Email).ToList().Count > 0)
                {
                    ViewBag.RoleId = new SelectList(_databaseConnection.Roles.ToList(), "RoleId", "Name",
                                                    appUser.RoleId);
                    TempData["display"]          = "A user with the same email already exist!";
                    TempData["notificationtype"] = NotificationType.Error.ToString();
                    return(View(appUser));
                }

                //upload user logo if any file is uploaded
                if (ProfilePicture != null && !string.IsNullOrEmpty(ProfilePicture.FileName))
                {
                    var fileInfo      = new FileInfo(ProfilePicture.FileName);
                    var ext           = fileInfo.Extension.ToLower();
                    var name          = DateTime.Now.ToFileTime().ToString();
                    var fileName      = name + ext;
                    var uploadedImage = _hostingEnv.WebRootPath + $@"\UploadedFiles\ProfilePicture\{fileName}";

                    using (var fs = System.IO.File.Create(uploadedImage))
                    {
                        if (fs != null)
                        {
                            ProfilePicture.CopyTo(fs);
                            fs.Flush();
                            appUser.ProfilePicture = fileName;
                        }
                    }
                }

                _databaseConnection.AppUsers.Add(appUser);
                _databaseConnection.SaveChanges();


                if (appUser.AppUserId > 0)
                {
                    //define acceskeys and save transactions
                    var accessKey = new AppUserAccessKey
                    {
                        PasswordAccessCode          = new Md5Ecryption().RandomString(15),
                        AccountActivationAccessCode = new Md5Ecryption().RandomString(20),
                        CreatedBy        = appUser.AppUserId,
                        LastModifiedBy   = appUser.AppUserId,
                        DateCreated      = DateTime.Now,
                        DateLastModified = DateTime.Now,
                        ExpiryDate       = DateTime.Now.AddDays(1),
                        AppUserId        = appUser.AppUserId
                    };
                    _databaseConnection.AppUserAccessKeys.Add(accessKey);
                    _databaseConnection.SaveChanges();
                    new Mailer().SendNewUserEmail(new AppConfig().NewUserHtml, appUser, accessKey);
                }

                TempData["display"]          = "You have successfully added a new user!";
                TempData["notificationtype"] = NotificationType.Success.ToString();
                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ViewBag.RoleId = new SelectList(_databaseConnection.Roles.ToList(), "RoleId", "Name", appUser.RoleId);
                //display notification
                TempData["display"]          = ex.Message;
                TempData["notificationtype"] = NotificationType.Error.ToString();
                return(View(appUser));
            }
        }