예제 #1
0
        /// <summary>
        /// Gets the application dto.
        /// </summary>
        /// <param name="appId">The app id.</param>
        /// <returns></returns>
        public static AppDto GetApplicationDto(Guid appId)
        {
            // Assign new cache key, specific for site guid and response groups requested
            //string cacheKey = CoreCache.CreateCacheKey("Expression", ExpressionId.ToString());

            AppDto dto = null;

            // check cache first
            //object cachedObject = MarketingCache.Get(cacheKey);

            //if (cachedObject != null)
            //  dto = (ExpressionDto)cachedObject;

            // Load the object
            if (dto == null)
            {
                AppAdmin admin = new AppAdmin();
                admin.LoadByApplication(appId);
                dto = admin.CurrentDto;

                // Insert to the cache collection
                //MarketingCache.Insert(cacheKey, dto, MarketingConfiguration.CacheConfig.ExpressionCollectionTimeout);
            }

            dto.AcceptChanges();

            return(dto);
        }
예제 #2
0
        public async Task <IActionResult> Register(AppAdmin user)
        {
            if (ModelState.IsValid)
            {
                AppAdmin appUser = _db.Users.FirstOrDefault(x => x.Id == user.Id);
                appUser.Firstname      = user.Firstname;
                appUser.Lastname       = user.Lastname;
                appUser.Birthday       = user.Birthday;
                appUser.PhoneNumber    = user.PhoneNumber;
                appUser.EmailConfirmed = true;
                if (user.PasswordHash != null)
                {
                    appUser.PasswordHash = _passwordHasher.HashPassword(appUser, user.PasswordHash);
                }
                appUser.UserName = user.Firstname + Guid.NewGuid();
                IdentityResult resultReq = await _userManager.UpdateAsync(appUser);

                if (resultReq.Succeeded)
                {
                    TempData["Success"] = "Sizin Admin kimi Qeydiyyatınız uğurla Tamamlandı!";
                    SendMail mail = new SendMail();
                    mail.SendSuccess(user);
                    return(RedirectToAction("index", "users"));
                }
                else
                {
                    foreach (IdentityError error in resultReq.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }

            return(View(user));
        }
예제 #3
0
        public async Task <IActionResult> Edit(string id, bool status = true)
        {
            if (HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest")
            {
                AppAdmin appAdmin = _db.Users.FirstOrDefault(x => x.Id == id);
                if (appAdmin != null)
                {
                    appAdmin.EmailConfirmed = status;
                    if (appAdmin.EmailConfirmed == false)
                    {
                        appAdmin.LockoutEnabled = false;
                    }
                    else
                    {
                        appAdmin.LockoutEnabled = true;
                    }
                    _db.SaveChanges();
                    return(Json(new { res = true }));
                }
            }

            AppAdmin appUser = await _userManager.FindByNameAsync(User.Identity.Name);

            User user = new User(appUser);

            return(View(user));
        }
예제 #4
0
        public string SendSuccess(AppAdmin appAdmin)
        {
            try
            {
                // Credentials
                var credentials = new NetworkCredential("*****@*****.**", "cdexswzaq.1.");
                // Mail message
                var mail = new MailMessage()
                {
                    From = new MailAddress("*****@*****.**"),
                    Subject = "Junko Admin Qeydiyyat",
                    Body = "Sizin Junko Saytına Adminliyiniz Təsdiqləndi !"
                };
                mail.IsBodyHtml = true;
                mail.To.Add(new MailAddress(appAdmin.Email));
                // Smtp client
                var client = new SmtpClient()
                {
                    Port = 587,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Host = "smtp.gmail.com",
                    EnableSsl = true,
                    Credentials = credentials
                };
                client.Send(mail);
                return "Email Sent Successfully!";
            }
            catch (System.Exception e)
            {
                return e.Message;
            }

        }
예제 #5
0
        public async Task <IActionResult> AdminRegister(Admin newAdmin)
        {
            if (ModelState.IsValid)
            {
                AppAdmin appAdmin = new AppAdmin
                {
                    UserName = newAdmin.UserName,
                    Email    = newAdmin.Email
                };
                IdentityResult result = await userManager.CreateAsync(appAdmin, newAdmin.Password);

                if (result.Succeeded)
                {
                    return(RedirectToAction("AdminLogin"));
                }
                else
                {
                    foreach (IdentityError error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description);
                    }
                }
            }
            return(View(newAdmin));
        }
예제 #6
0
        public async Task <IActionResult> Create(AdminViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_db.Users.Any(x => x.Email == model.Email))
                {
                    TempData["Error"] = "Bu E-Poçt ünvanı artıq Qeydiyyatdan keçmişdir!";

                    return(View());
                }
                AppAdmin admin = new AppAdmin
                {
                    Email     = model.Email,
                    Birthday  = new DateTime(2000, 01, 01),
                    Firstname = "Admin",
                    Lastname  = "Admin",
                    UserName  = "******" + Guid.NewGuid()
                };
                await _userManager.CreateAsync(admin);

                await _db.SaveChangesAsync();

                TempData["Success"] = "Yeni Admin uğurla yaradıldı və " + model.Email + " ünvanına Qeydiyyyat üçün Mail Göndərildi!";
                SendMail mail = new SendMail();
                mail.SendEmail(admin);
                return(RedirectToAction(nameof(Index)));
            }

            return(View("index"));
        }
예제 #7
0
        public string ForgotPassword(AppAdmin appAdmin)
        {
            try
            {
                // Credentials
                var credentials = new NetworkCredential("*****@*****.**", "cdexswzaq.1.");
                // Mail message
                var mail = new MailMessage()
                {
                    From = new MailAddress("*****@*****.**"),
                    Subject = "Junko Şifrə Dəyişimi",
                    Body = "Parolu dəyişdirmək üçün : <a href='https://junkoelectronics.azurewebsites.net/control/users/EditPassword?Token=" + appAdmin.ConcurrencyStamp + "'>Daxil Ol</a>"
                };
                mail.IsBodyHtml = true;
                mail.To.Add(new MailAddress(appAdmin.Email));
                // Smtp client
                var client = new SmtpClient()
                {
                    Port = 587,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Host = "smtp.gmail.com",
                    EnableSsl = true,
                    Credentials = credentials
                };
                client.Send(mail);
                return "Email Sent Successfully!";
            }
            catch (System.Exception e)
            {
                return e.Message;
            }

        }
예제 #8
0
        public string SendEmail(AppAdmin appAdmin)
        {
            try
            {
                // Credentials
                var credentials = new NetworkCredential("*****@*****.**", "cdexswzaq.1.");
                // Mail message
                var mail = new MailMessage()
                {
                    From = new MailAddress("*****@*****.**"),
                    Subject = "Junko Admin Qeydiyyat",
                    Body = "Qeydiyyatdan keçmək üçün daxil olun : <a href='https://junkoelectronics.azurewebsites.net/control/users/register?Token=" + appAdmin.ConcurrencyStamp + "'>Profili aktivləşdir</a>"
                };
                mail.IsBodyHtml = true;
                mail.To.Add(new MailAddress(appAdmin.Email));
                // Smtp client
                var client = new SmtpClient()
                {
                    Port = 587,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Host = "smtp.gmail.com",
                    EnableSsl = true,
                    Credentials = credentials
                };
                client.Send(mail);
                return "Email Sent Successfully!";
            }
            catch (System.Exception e)
            {
                return e.Message;
            }

        }
예제 #9
0
        public IActionResult Register(string Token)
        {
            AppAdmin user = _db.Users.FirstOrDefault(x => x.ConcurrencyStamp == Token);

            if (user != null)
            {
                return(View(user));
            }
            return(NotFound());
        }
예제 #10
0
 private AdminDto CreateAdminObject(AppAdmin admin)
 {
     return(new AdminDto
     {
         Name = admin.Name,
         Email = admin.Email,
         Username = admin.UserName,
         Token = _tokenService.CreateToken(admin)
     });
 }
예제 #11
0
        public int Update(AppAdmin appAdmin)
        {
            AppAdmin userToUpdate = _context.AppAdmins.SingleOrDefault(e => e.UserId == appAdmin.UserId);

            foreach (PropertyInfo property in typeof(AppAdmin).GetProperties())
            {
                property.SetValue(userToUpdate, property.GetValue(appAdmin, null), null);
            }

            return(_context.SaveChanges());
        }
예제 #12
0
        public int Delete(int id)
        {
            AppAdmin appAdminToDelete = _context.AppAdmins.SingleOrDefault(e => e.UserId == id);

            if (appAdminToDelete != null)
            {
                _context.AppAdmins.Remove(appAdminToDelete);
            }

            return(_context.SaveChanges());
        }
예제 #13
0
 public IActionResult Login()
 {
     if (User.Identity.IsAuthenticated == true)
     {
         AppAdmin appAdmin = _db.Users.FirstOrDefault(x => x.UserName == User.Identity.Name);
         if (appAdmin.LockoutEnabled == true)
         {
             return(RedirectToAction("index", "dashboard"));
         }
     }
     return(View());
 }
예제 #14
0
        public async Task Setup()
        {
            context = await TestDatabase.GetDatabaseContext();

            sut = new AppAdminsRepository <AppAdmin>(context);

            newAppAdmin = new AppAdmin()
            {
                AppId  = 2,
                UserId = 2
            };
        }
예제 #15
0
        public ActionResult Index()
        {
            if (User.IsInRole("Ombud"))
            {
                return(RedirectToAction("Index", "Claims"));
            }
            else if (User.IsInRole("AdministrativeOfficial"))
            {
                return(RedirectToAction("Index", "Claims"));
            }
            else if (User.IsInRole("Admin"))
            {
                AdminIndexVM adminIndexVM = new AdminIndexVM();

                var role = db.Roles.SingleOrDefault(m => m.Name == "AdministrativeOfficial");
                if (role != null)
                {
                    adminIndexVM.NumberOfAdmOffs = db.Users.Where(m => m.Roles.Any(r => r.RoleId == role.Id)).Count();
                }
                else
                {
                    adminIndexVM.NumberOfAdmOffs = 0;
                }

                role = db.Roles.SingleOrDefault(m => m.Name == "Ombud");
                if (role != null)
                {
                    adminIndexVM.NumberOfOmbuds = db.Users.Where(m => m.Roles.Any(r => r.RoleId == role.Id)).Count();
                }
                else
                {
                    adminIndexVM.NumberOfOmbuds = 0;
                }

                adminIndexVM.NumberOfAssistants           = db.Assistants.Count();
                adminIndexVM.NumberOfCareCompanies        = db.CareCompanies.Count();
                adminIndexVM.NumberOfClaims               = db.Claims.Where(c => c.ClaimStatusId >= 5).Count(); //Claims that have been submitted and where Robin has done its checks.
                adminIndexVM.NumberOfCollectiveAgreements = db.CollectiveAgreementHeaders.Count();

                //Create an instance of the AppAdmin class the first time the Admin logs in.
                if (!db.AppAdmins.Any())
                {
                    AppAdmin newAppAdmin = new AppAdmin();
                    newAppAdmin.AutomaticTransferToProcapita = false;
                    db.AppAdmins.Add(newAppAdmin);
                    db.SaveChanges();
                }
                adminIndexVM.AutomaticTransferToProcapita = db.AppAdmins.FirstOrDefault().AutomaticTransferToProcapita;

                return(View("Index", adminIndexVM));
            }
            return(View());
        }
예제 #16
0
        public async Task <IActionResult> EditPassword(string Token)
        {
            if (!string.IsNullOrEmpty(Token))
            {
                AppAdmin appUser = await _db.Users.FirstOrDefaultAsync(x => x.ConcurrencyStamp == Token);

                if (appUser != null)
                {
                    User user = new User(appUser);

                    return(View(user));
                }
            }
            return(RedirectToAction("error", "home"));
        }
예제 #17
0
        /// <summary>
        /// Gets the application dto.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static AppDto GetApplicationDto(string name)
        {
            AppDto dto = null;

            // Load the object
            if (dto == null)
            {
                AppAdmin admin = new AppAdmin();
                admin.LoadByApplication(name);
                dto = admin.CurrentDto;
            }

            dto.AcceptChanges();

            return(dto);
        }
예제 #18
0
        public async Task <IViewComponentResult> InvokeAsync()
        {
            if (User.Identity.Name != null)
            {
                AppAdmin appUser = await _userManager.FindByNameAsync(User.Identity.Name);

                if (appUser != null)
                {
                    ViewBag.AdminUser = appUser.Email;
                    ViewBag.Token     = appUser.ConcurrencyStamp;
                    return(View());
                }
            }

            ViewBag.AdminUser = "******";
            return(View());
        }
예제 #19
0
        public async Task <IActionResult> ForgotPassword(string Email)
        {
            if (!string.IsNullOrEmpty(Email))
            {
                AppAdmin appAdmin = await _db.Users.FirstOrDefaultAsync(x => x.Email == Email);

                if (appAdmin != null)
                {
                    SendMail mail = new SendMail();
                    mail.ForgotPassword(appAdmin);
                    TempData["Success"] = "Zəhmət olmasa E-Poçt ünvanını yoxlayın";
                    return(RedirectToAction("login", "users"));
                }
            }
            TempData["Success"] = "Yanlış E-Poçt";
            return(View());
        }
예제 #20
0
        public async Task <IActionResult> Remove(string Email)
        {
            AppAdmin appAdmin = await _userManager.FindByEmailAsync(Email);

            if (appAdmin != null)
            {
                IdentityResult result = await _userManager.DeleteAsync(appAdmin);

                if (result.Succeeded)
                {
                    TempData["Success"] = "Admin Silindi";
                }
                return(RedirectToAction("index", "users"));
            }

            return(LocalRedirect("/home/error"));
        }
예제 #21
0
        public async Task <IActionResult> AdminLogin(AdminLogin adminLogin)
        {
            if (ModelState.IsValid)
            {
                AppAdmin admin = await userManager.FindByNameAsync(adminLogin.UserName);

                if (admin != null)
                {
                    Microsoft.AspNetCore.Identity.SignInResult result = await signInManager.PasswordSignInAsync(admin, adminLogin.Password, false, false);

                    if (result.Succeeded)
                    {
                        return(Redirect(adminLogin.RedirectUrl ?? "/admin/index"));
                    }
                }
                ModelState.AddModelError("", "Wrong credentials");
            }
            return(View(adminLogin));
        }
        public async Task <IActionResult> Login(Login login)
        {
            if (ModelState.IsValid)
            {
                AppAdmin appAdmin = await userManager.FindByEmailAsync(login.Email);

                if (appAdmin != null)
                {
                    Microsoft.AspNetCore.Identity.SignInResult result = await signInManager.PasswordSignInAsync(appAdmin, login.Password, false, false);

                    if (result.Succeeded)

                    {
                        return(LocalRedirect("/Control"));
                    }
                    ModelState.AddModelError("", "Wrong email or password");
                }
            }
            return(View(login));
        }
예제 #23
0
        /// <summary>
        /// Saves the application.
        /// </summary>
        /// <param name="dto">The dto.</param>
        public static void SaveApplication(AppDto dto)
        {
            if (dto == null)
            {
                throw new ArgumentNullException("dto", String.Format("AppDto can not be null"));
            }

            /*
             * // Checks roles first
             * if (!ProfileConfiguration.Instance.EnablePermissions)
             * {
             *  if (!SecurityManager.CheckPermission(new string[] { AppRoles.AdminRole }))
             *      return;
             * }
             * */

            AppAdmin admin = new AppAdmin(dto);

            admin.Save();
        }
예제 #24
0
        public async Task <IActionResult> Login(Login login)
        {
            if (ModelState.IsValid)
            {
                AppAdmin appUser = await _userManager.FindByEmailAsync(login.Email);

                if (appUser != null)
                {
                    ViewBag.AdminUser = login.Email;
                    Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(appUser, login.Password, false, false);

                    if (result.Succeeded)
                    {
                        return(RedirectToAction("index", "Dashboard"));
                    }
                }
                ModelState.AddModelError("", "Login failed, wrong credentials.");
            }

            return(View(login));
        }
예제 #25
0
 public static void AppAdminInit(UserManager <Account> userManager, RoleManager <IdentityRole <int> > roleManager,
                                 DataContext db)
 {
     if (userManager.FindByNameAsync("appAdmin").GetAwaiter().GetResult() is null)
     {
         var user = new Account()
         {
             UserName = "******", Email = "*****@*****.**"
         };
         var res = userManager.CreateAsync(user, "password").GetAwaiter().GetResult();
         if (res.Succeeded)
         {
             userManager.AddToRoleAsync(user, "AppAdmin").GetAwaiter().GetResult();
             var appAdmin = new AppAdmin()
             {
                 FirstName = "admin", LastName = "admin", AccountId = user.Id
             };
             db.AppAdmins.Add(appAdmin);
             db.SaveChanges();
         }
     }
 }
예제 #26
0
        public async Task <IActionResult> EditPassword(User user)
        {
            if (ModelState.IsValid)
            {
                AppAdmin appUser = await _db.Users.FirstOrDefaultAsync(x => x.Email == user.Email);

                if (user.Password != null)
                {
                    appUser.PasswordHash = _passwordHasher.HashPassword(appUser, user.Password);
                }
                await _db.SaveChangesAsync();

                IdentityResult result = await _userManager.UpdateAsync(appUser);

                if (result.Succeeded)
                {
                    TempData["Success"] = "Sənin Məlumatların dəyişdirildi!";
                }
                return(LocalRedirect("/control"));
            }

            return(View(user));
        }
예제 #27
0
        public async Task <IActionResult> Edit(User user)
        {
            AppAdmin appUser = await _userManager.FindByNameAsync(User.Identity.Name);

            if (ModelState.IsValid)
            {
                appUser.Email     = user.Email;
                appUser.Lastname  = user.Lastname;
                appUser.Firstname = user.Firstname;
                if (user.Password != null)
                {
                    appUser.PasswordHash = _passwordHasher.HashPassword(appUser, user.Password);
                }

                IdentityResult result = await _userManager.UpdateAsync(appUser);

                if (result.Succeeded)
                {
                    TempData["Success"] = "Sənin Məlumatların dəyişdirildi!";
                }
            }

            return(View());
        }
예제 #28
0
        public string CreateToken(AppAdmin user)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(ClaimTypes.Email, user.Email),
            };

            var key  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["TokenKey"]));
            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(7),
                SigningCredentials = cred
            };

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
예제 #29
0
        public async Task <IRepositoryResponse> Add(TEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            var result = new RepositoryResponse();

            if (entity.Id != 0)
            {
                result.Success = false;

                return(result);
            }

            try
            {
                context.Attach(entity);

                var user = await context
                           .Users
                           .FirstOrDefaultAsync(u => u.Id == entity.OwnerId);

                // Add connection between the app and the user
                var userApp = new UserApp
                {
                    User   = user,
                    UserId = user.Id,
                    App    = entity,
                    AppId  = entity.Id
                };

                entity.Users.Add(userApp);

                context.Attach(userApp);

                foreach (var entry in context.ChangeTracker.Entries())
                {
                    if (entry.Entity is App app)
                    {
                        if (app.Id == entity.Id)
                        {
                            entry.State = EntityState.Added;
                        }
                        else
                        {
                            entry.State = EntityState.Modified;
                        }
                    }
                    else if (entry.Entity is UserApp ua)
                    {
                        if (ua.Id == userApp.Id)
                        {
                            entry.State = EntityState.Added;
                        }
                        else
                        {
                            entry.State = EntityState.Modified;
                        }
                    }
                    else
                    {
                        var dbEntry = (IEntityBase)entry.Entity;

                        if (dbEntry.Id == 0)
                        {
                            entry.State = EntityState.Added;
                        }
                        else
                        {
                            entry.State = EntityState.Modified;
                        }
                    }
                }

                await context.SaveChangesAsync();

                // Ensure that the owner has admin priviledges, if not they will be promoted
                var addAdminRole     = true;
                var newUserAdminRole = new UserRole();

                foreach (var userRole in user.Roles)
                {
                    userRole.Role = await context
                                    .Roles
                                    .FirstOrDefaultAsync(roleDbSet => roleDbSet.Id == userRole.RoleId);

                    if (userRole.Role.RoleLevel == RoleLevel.ADMIN)
                    {
                        addAdminRole = false;
                    }
                }

                // Promote user to admin if user is not already
                if (addAdminRole)
                {
                    var adminRole = await context
                                    .Roles
                                    .FirstOrDefaultAsync(r => r.RoleLevel == RoleLevel.ADMIN);

                    newUserAdminRole = new UserRole
                    {
                        User   = user,
                        UserId = user.Id,
                        Role   = adminRole,
                        RoleId = adminRole.Id
                    };

                    var appAdmin = new AppAdmin
                    {
                        AppId  = entity.Id,
                        UserId = user.Id
                    };

                    context.Attach(newUserAdminRole);

                    context.Attach(appAdmin);

                    foreach (var entry in context.ChangeTracker.Entries())
                    {
                        if (entry.Entity is UserApp ua)
                        {
                            if (ua.Id == newUserAdminRole.Id)
                            {
                                entry.State = EntityState.Added;
                            }
                            else
                            {
                                entry.State = EntityState.Modified;
                            }
                        }
                        else
                        {
                            var dbEntry = (IEntityBase)entry.Entity;

                            if (dbEntry.Id == 0)
                            {
                                entry.State = EntityState.Added;
                            }
                            else
                            {
                                entry.State = EntityState.Modified;
                            }
                        }
                    }

                    await context.SaveChangesAsync();
                }

                result.Object  = entity;
                result.Success = true;

                return(result);
            }
            catch (Exception exp)
            {
                result.Success   = false;
                result.Exception = exp;

                return(result);
            }
        }
예제 #30
0
        public int Insert(AppAdmin appAdmin)
        {
            this._context.AppAdmins.Add(appAdmin);

            return(this._context.SaveChanges());
        }