Esempio n. 1
0
        public async Task <ActionResult> TimeOut(string id)
        {
            var context = new SphDataContext();
            var user    = await context.LoadOneAsync <Pengguna>(x => x.MyKad == User.Identity.Name);

            var sesi = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var name    = user == null ? "" : user.Nama;
            var setting = (await context.LoadOneAsync <PercubaanSesi>(x => x.MyKad == User.Identity.Name && x.SesiUjianId == id))
                          ?? new PercubaanSesi
            {
                No           = Guid.NewGuid().ToString(),
                MyKad        = User.Identity.Name,
                SesiUjianId  = id,
                Bilangan     = 0,
                NamaUjian    = sesi.NamaUjian,
                Program      = sesi.NamaProgram,
                NamaPengguna = name,
                Tarikh       = DateTime.Now,
                Id           = Guid.NewGuid().ToString()
            };


            setting.Bilangan += 1;
            using (var session = context.OpenSession())
            {
                session.Attach(setting);
                await session.SubmitChanges();
            }


            return(Json(setting));
        }
Esempio n. 2
0
        private async Task <IpTraitViewModel> GetIpTraitViewModelAsync(string id)
        {
            var context = new SphDataContext();
            var sesi    = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var user = await context.LoadOneAsync <Pengguna>(x => x.MyKad == sesi.MyKad);

            var ujian = await context.LoadOneAsync <Ujian>(x => x.Id == sesi.NamaUjian);

            var permohonan = await context.LoadOneAsync <Permohonan>(x => x.PermohonanNo == sesi.NamaProgram);

            if (null == sesi || null == user)
            {
                return(null);
            }

            var vm = new IpTraitViewModel(sesi, user)
            {
                Permohonan = permohonan,
                Ujian      = ujian
            };

            vm.Recommendation = await context.LoadOneAsync <IpRecommendation>(x => x.Skor == vm.Result);

            if (null == vm.Recommendation)
            {
                throw new InvalidOperationException("Cannot find IpRecommendation for " + vm.Result);
            }

            return(vm);
        }
        public async Task <ActionResult> PrintIndikatorIso(string id)
        {
            var context = new SphDataContext();
            var sesi    = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var user = await context.LoadOneAsync <Pengguna>(x => x.MyKad == sesi.MyKad);

            var ujianTask          = context.LoadOneAsync <Ujian>(x => x.Id == sesi.NamaUjian);
            var permohonanTask     = context.LoadOneAsync <Permohonan>(x => x.PermohonanNo == sesi.NamaProgram);
            var recommendationTask = context.LoadAsync(context.CreateQueryable <IsoRecommendation>());
            var soalanTask         = context.LoadAsync(context.CreateQueryable <Soalan>().Where(x => x.NamaUjian == "Inventori Stres Organisasi (ISO)"), 1, 120, true);
            await Task.WhenAll(ujianTask, permohonanTask, recommendationTask, soalanTask);

            var rlo      = await recommendationTask;
            var soalanLo = await soalanTask;

            if (null == sesi)
            {
                return(HttpNotFound("Cannot find SesiUjian " + id));
            }
            if (null == user)
            {
                return(HttpNotFound("Cannot find user with MyKad " + sesi.MyKad));
            }

            var vm = new IsoTraitViewModel(sesi, user, rlo.ItemCollection, soalanLo.ItemCollection)
            {
                Permohonan = await permohonanTask,
                Ujian      = await ujianTask,
                Pengguna   = user
            };

            return(View("Indikator-Iso", vm));
        }
        public async Task <ActionResult> PrintPpkpKhusus(string id)
        {
            var context = new SphDataContext();
            var sesi    = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var user = await context.LoadOneAsync <Pengguna>(x => x.MyKad == sesi.MyKad);

            var ujianTask          = context.LoadOneAsync <Ujian>(x => x.Id == sesi.NamaUjian);
            var permohonanTask     = context.LoadOneAsync <Permohonan>(x => x.PermohonanNo == sesi.NamaProgram);
            var recommendationTask = context.LoadAsync(context.CreateQueryable <PpkpRecommendation>());
            var skorTask           = context.LoadAsync(context.CreateQueryable <SkorPpkp>(), 1, 150, true);
            await Task.WhenAll(ujianTask, permohonanTask, recommendationTask, skorTask);

            var rlo    = await recommendationTask;
            var skorLo = await skorTask;

            if (null == sesi)
            {
                return(HttpNotFound("Cannot find SesiUjian " + id));
            }
            if (null == user)
            {
                return(HttpNotFound("Cannot find user with MyKad " + sesi.MyKad));
            }

            var vm = new PpkpTraitViewModel(sesi, rlo.ItemCollection.ToArray(), skorLo.ItemCollection.ToArray())
            {
                Permohonan = await permohonanTask,
                Ujian      = await ujianTask,
                Pengguna   = user
            };

            return(View("ppkp.khusus", vm));
        }
Esempio n. 5
0
        public async Task <ActionResult> PrintTraitForHlp(string id)
        {
            var context = new SphDataContext();
            var sesi    = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var user = await context.LoadOneAsync <Pengguna>(x => x.MyKad == sesi.MyKad);

            var ujianTask      = context.LoadOneAsync <Bespoke.epsikologi_ujian.Domain.Ujian>(x => x.Id == sesi.NamaUjian);
            var permohonanTask =
                context.LoadOneAsync <Bespoke.epsikologi_permohonan.Domain.Permohonan>(
                    x => x.PermohonanNo == sesi.NamaProgram);
            await Task.WhenAll(ujianTask, permohonanTask);

            var query = context.CreateQueryable <SkorHlp>();
            var lo    = await context.LoadAsync(query, size : 1000);

            var scoreTables = lo.ItemCollection;


            var rq  = context.CreateQueryable <HlpRecomendation>();
            var rlo = await context.LoadAsync(rq, size : 200);

            var recommendations = rlo.ItemCollection;


            if (null == sesi)
            {
                return(HttpNotFound("Cannot find SesiUjian " + id));
            }
            if (null == user)
            {
                return(HttpNotFound("Cannot find user with MyKad " + sesi.MyKad));
            }

            var vm = new HlpTraitViewModel(sesi, user, scoreTables.ToArray(), recommendations.ToArray())
            {
                Permohonan = await permohonanTask,
                Ujian      = await ujianTask
            };

            var viewName = "Trait-Hlp-" + user.Jantina;

            //   const string STYLE = "border:3px solid red";
            //    return Pdf(viewName, vm, "~/Views/PrintReport/_MasterPage.NoHeader.cshtml",
            //    x => x
            //        .Replace($"id=\"KB{vm.KB.Point}\"", $"id=\"KB{vm.KB.Point}\"      style=\"{STYLE}\"")
            //        .Replace($"id=\"FR{vm.FR.Percentile}\"", $"id=\"FR{vm.FR.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"KT{vm.KT.Percentile}\"", $"id=\"KT{vm.KT.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"KC{vm.KC.Percentile}\"", $"id=\"KC{vm.KC.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"LP{vm.LP.Percentile}\"", $"id=\"LP{vm.LP.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"SM{vm.SM.Percentile}\"", $"id=\"SM{vm.SM.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"AS{vm.AS.Percentile}\"", $"id=\"AS{vm.AS.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"AF{vm.AF.Percentile}\"", $"id=\"AF{vm.AF.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"TL{vm.TL.Percentile}\"", $"id=\"TL{vm.TL.Percentile}\" style=\"{STYLE}\"")
            //        .Replace($"id=\"DT{vm.DT.Percentile}\"", $"id=\"DT{vm.DT.Percentile}\" style=\"{STYLE}\""), true);

            return(View(viewName, vm));
        }
Esempio n. 6
0
        public async Task <ActionResult> Html(string id)
        {
            var context = new SphDataContext();
            var form    = await context.LoadOneAsync <EntityForm>(f => f.Route == id);

            var ed = await context.LoadOneAsync <EntityDefinition>(f => f.Id == form.EntityDefinitionId);

            var layout = string.IsNullOrWhiteSpace(form.Layout) ? "Html2ColsWithAuditTrail" : form.Layout;
            var vm     = new FormRendererViewModel(ed, form);

            return(View(layout, vm));
        }
Esempio n. 7
0
        public async Task <ActionResult> UpdateUser(UserProfile profile)
        {
            var context     = new SphDataContext();
            var userprofile = await context.LoadOneAsync <UserProfile>(p => p.UserName == User.Identity.Name)
                              ?? new UserProfile();

            userprofile.UserName    = User.Identity.Name;
            userprofile.Email       = profile.Email;
            userprofile.Telephone   = profile.Telephone;
            userprofile.FullName    = profile.FullName;
            userprofile.StartModule = profile.StartModule;
            userprofile.Language    = profile.Language;

            if (userprofile.IsNewItem)
            {
                userprofile.Id = userprofile.UserName.ToIdFormat();
            }

            using (var session = context.OpenSession())
            {
                session.Attach(userprofile);
                await session.SubmitChanges();
            }
            this.Response.ContentType = "application/json; charset=utf-8";
            return(Content(JsonConvert.SerializeObject(userprofile)));
        }
Esempio n. 8
0
        public async Task <ActionResult> ResetPassword(string id)
        {
            var context = new SphDataContext();
            var setting = await context.LoadOneAsync <Setting>(x => x.Id == id);

            var model = new ResetPaswordModel {
                IsValid = true, Id = id
            };

            if (null == setting)
            {
                model.IsValid = false;
                model.Mesage  = "The link is invalid";
                return(View(model));
            }

            model.Email = setting.UserName;
            if ((DateTime.Now - setting.CreatedDate).TotalMinutes > 10)
            {
                model.IsValid = false;
                model.Mesage  = "The link has expired";
                return(View(model));
            }
            var user = Membership.FindUsersByEmail(setting.UserName);

            if (user.Count == 0)
            {
                model.IsValid = false;
                model.Mesage  = "Cannot find any user with email  " + model.Email;
            }
            model.Email = setting.UserName;
            return(View(model));
        }
Esempio n. 9
0
        private async Task <UserProfile> GetDesignation()
        {
            var username    = User.Identity.Name;
            var directory   = new SphDataContext();
            var userProfile = await directory.LoadOneAsync <UserProfile>(p => p.UserName == username) ?? new UserProfile();

            return(userProfile);
        }
        public async Task <ActionResult> CountForRespondenDariJabatan()
        {
            var context    = new SphDataContext();
            var penyelaras = await context.LoadOneAsync <Pengguna>(x => x.MyKad == User.Identity.Name);

            var count = await context.GetCountAsync <Pengguna>(x => x.NamaJabatan == penyelaras.NamaJabatan);

            return(Json(new { hits = new { total = count } }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 11
0
        private static async Task <OstRegisterStatusModel> CreateAccount(OstRegisterModel model)
        {
            var result = new OstRegisterStatusModel
            {
                Success = true,
                Status  = "OK"
            };

            Profile profile = new Profile();

            profile.UserName = model.UserName;
            profile.FullName = model.FullName;
            profile.Email    = model.Email;
            profile.Password = model.Password;

            var context     = new SphDataContext();
            var designation = await context.LoadOneAsync <Designation>(d => d.Name == model.Designation);

            if (null == designation)
            {
                result.Success = false;
                result.Status  = $"Cannot find designation {model.Designation}";
                return(result);
            }

            profile.Designation = model.Designation;
            profile.Roles       = designation.RoleCollection.ToArray();

            var em = Membership.GetUser(profile.UserName);

            if (null != em)
            {
                result.Success = false;
                result.Status  = $"User {profile.UserName} already exist.";
                return(result);
            }

            try
            {
                Membership.CreateUser(profile.UserName, profile.Password, profile.Email);
            }
            catch (MembershipCreateUserException ex)
            {
                ObjectBuilder.GetObject <ILogger>().Log(new LogEntry(ex));
                result.Success = false;
                result.Status  = ex.Message;
                return(result);
            }

            Roles.AddUserToRoles(profile.UserName, profile.Roles);
            await CreateProfile(profile, designation);

            return(result);
        }
    private static async Task <bool> AddUserAsync(Profile profile)
    {
        var context  = new SphDataContext();
        var userName = profile.UserName;

        if (string.IsNullOrWhiteSpace(profile.Designation))
        {
            throw new ArgumentNullException("Designation for  " + userName + " cannot be set to null or empty");
        }
        var designation = await context.LoadOneAsync <Designation>(d => d.Name == profile.Designation);

        if (null == designation)
        {
            throw new InvalidOperationException("Cannot find designation " + profile.Designation);
        }
        var roles = designation.RoleCollection.ToArray();

        var em = Membership.GetUser(userName);

        if (null != em)
        {
            profile.Roles = roles;
            em.Email      = profile.Email;

            var originalRoles = Roles.GetRolesForUser(userName);
            if (originalRoles.Length > 0)
            {
                Roles.RemoveUserFromRoles(userName, originalRoles);
            }

            Roles.AddUserToRoles(userName, profile.Roles);
            Membership.UpdateUser(em);
            await CreateProfile(profile, designation);

            return(true);
        }

        try
        {
            Membership.CreateUser(userName, profile.Password, profile.Email);
        }
        catch (MembershipCreateUserException ex)
        {
            ObjectBuilder.GetObject <ILogger>().Log(new LogEntry(new Exception($"Fail to create User for device '{userName}', email :'{profile.Email}' and password : '******'", ex)));
            return(false);
        }

        Roles.AddUserToRoles(userName, roles);
        profile.Roles = roles;

        await CreateProfile(profile, designation);

        return(true);
    }
Esempio n. 13
0
        public async Task <ActionResult> Index()
        {
            var context = new SphDataContext();
            var profile = await context.LoadOneAsync <UserProfile>(ua => ua.UserName == User.Identity.Name);

            if (null == profile)
            {
                return(View("Default", new JpaHomeViewModel {
                    Designation = new Designation {
                        IsHelpVisible = false
                    }
                }));
            }


            var designation = (await context.LoadOneAsync <Designation>(d => d.Name == profile.Designation)) ?? new Designation {
                IsHelpVisible = true, HelpUri = "/docs/"
            };

            designation.HelpUri = string.IsNullOrWhiteSpace(designation.HelpUri) ? "/docs/" : designation.HelpUri;

            var query      = context.CreateQueryable <Message>();
            var messagesLo = await context.LoadAsync(query.Where(x => x.UserName == User.Identity.Name && x.IsRead == false), 1, 5, true);


            var vm = new JpaHomeViewModel
            {
                Profile           = profile,
                Designation       = designation,
                StartModule       = "#" + profile.StartModule,
                TotalMessageCount = messagesLo.TotalRows ?? 0
            };

            vm.Messages.AddRange(messagesLo.ItemCollection);
            if (this.User.IsInRole("Developers"))
            {
                return(Redirect("/sph#dev.home"));
            }

            return(View("Default", vm));
        }
Esempio n. 14
0
        public async Task <ActionResult> ChangePassword(ChangePaswordModel model)
        {
            var userName = User.Identity.Name;

            if (!Membership.ValidateUser(userName, model.OldPassword))
            {
                return(Json(new { success = false, status = "PASSWORD_INCORRECT", message = "Your old password is incorrect", user = userName }));
            }
            if (model.Password != model.ConfirmPassword)
            {
                return(Json(new { success = false, status = "PASSWORD_DOESNOT_MATCH", message = "Your password is not the same" }));
            }


            var user = Membership.GetUser(userName);

            if (null == user)
            {
                throw new Exception("Cannot find user");
            }

            try
            {
                var valid = user.ChangePassword(model.OldPassword, model.Password);
                if (!valid)
                {
                    return(Json(new { success = false, status = "ERROR_CHANGING_PASSWORD", message = "There's an error changing your password" }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, status = "EXCEPTION_CHANGING_PASSWORD", message = ex.Message }));
            }

            var context = new SphDataContext();
            var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == User.Identity.Name);

            profile.HasChangedDefaultPassword = true;

            using (var session = context.OpenSession())
            {
                session.Attach(profile);
                await session.SubmitChanges("Change password");
            }

            if (Request.ContentType.Contains("application/json"))
            {
                this.Response.ContentType = "application/json; charset=utf-8";
                return(Content(JsonConvert.SerializeObject(new { success = true, status = "OK" })));
            }

            return(Redirect("/"));
        }
Esempio n. 15
0
        public async Task <ActionResult> PrintSesiUjianIndikator(string id)
        {
            var context = new SphDataContext();
            var sesi    = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            if (null == sesi)
            {
                return(HttpNotFound("Cannot find SesiUjian " + id));
            }

            return(View("Indikator-" + sesi.NamaUjian, sesi));
        }
Esempio n. 16
0
        public async Task <ActionResult> Login(JpaLoginModel model, string returnUrl)
        {
            var logger = ObjectBuilder.GetObject <ILogger>();

            if (ModelState.IsValid)
            {
                var directory = ObjectBuilder.GetObject <IDirectoryService>();
                if (await directory.AuthenticateAsync(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    var context = new SphDataContext();
                    var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == model.UserName);

                    await logger.LogAsync(new LogEntry { Log = EventLog.Security });

                    if (null != profile)
                    {
                        if (!profile.HasChangedDefaultPassword)
                        {
                            return(RedirectToAction("ChangePassword"));
                        }
                        if (returnUrl == "/" ||
                            returnUrl.Equals("/epsikologi", StringComparison.InvariantCultureIgnoreCase) ||
                            returnUrl.Equals("/epsikologi#", StringComparison.InvariantCultureIgnoreCase) ||
                            returnUrl.Equals("/epsikologi/", StringComparison.InvariantCultureIgnoreCase) ||
                            returnUrl.Equals("/epsikologi/#", StringComparison.InvariantCultureIgnoreCase) ||
                            string.IsNullOrWhiteSpace(returnUrl))
                        {
                            return(Redirect("/epsikologi#" + profile.StartModule));
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    return(Redirect("epsikologi#"));
                }
                var user = await directory.GetUserAsync(model.UserName);

                await logger.LogAsync(new LogEntry { Log = EventLog.Security, Message = "Login Failed" });

                if (null != user && user.IsLockedOut)
                {
                    ModelState.AddModelError("", "Your acount has beeen locked, Please contact your administrator.");
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            return(View(model));
        }
Esempio n. 17
0
        //exec:6527072e-1302-4de8-cdbe-52968cfea0a4
        public async Task <ActivityExecutionResult> CreateProfileAndMembershipAsync()
        {
            var result = new ActivityExecutionResult {
                Status = ActivityExecutionStatus.Success
            };
            var item = this;

            var context     = new SphDataContext();
            var designation = await context.LoadOneAsync <Designation>(d => d.Name == "Responden");

            var roles   = designation.RoleCollection.ToArray();
            var profile = new UserProfile
            {
                Id          = this.Pengguna.Id,
                UserName    = this.Pengguna.MyKad,
                Email       = this.Pengguna.Emel,
                FullName    = this.Pengguna.Nama,
                Designation = "Responden",
                HasChangedDefaultPassword = false,
                RoleTypes   = string.Join(",", roles),
                StartModule = "responden-home",
                Language    = "en-US"
            };

            Console.WriteLine("done mapping user profile");

            var exist            = System.Web.Security.Membership.GetUser(profile.UserName);
            var existUserByEmail = System.Web.Security.Membership.GetUserNameByEmail(profile.Email);


            if ((null == exist) || (null == existUserByEmail))
            {
                this.Password = System.Web.Security.Membership.GeneratePassword(6, 0);

                System.Web.Security.Membership.CreateUser(profile.UserName, this.Password, profile.Email);
                System.Web.Security.Roles.AddUserToRoles(profile.UserName, roles);

                Console.WriteLine("insert into user profile");
                using (var session = context.OpenSession())
                {
                    session.Attach(profile);
                    await session.SubmitChanges();
                }

                //IsCreated = true;
            }

            result.NextActivities = new[] { "41cddfd4-0781-44b1-db25-cbef78c61352" };


            return(result);
        }
Esempio n. 18
0
        private static async Task SetVerifyEmailFlag(string username)
        {
            var context     = new SphDataContext();
            var userProfile = await context.LoadOneAsync <UserProfile>(p => p.UserName == username);

            if (!userProfile.HasChangedDefaultPassword)
            {
                userProfile.HasChangedDefaultPassword = true;
                using (var session = context.OpenSession())
                {
                    session.Attach(userProfile);
                    await session.SubmitChanges();
                }
            }
        }
    private static async Task <UserProfile> CreateProfile(Profile profile, Designation designation)
    {
        if (null == profile)
        {
            throw new ArgumentNullException(nameof(profile));
        }
        if (null == designation)
        {
            throw new ArgumentNullException(nameof(designation));
        }
        if (string.IsNullOrWhiteSpace(designation.Name))
        {
            throw new ArgumentNullException(nameof(designation), "Designation Name cannot be null, empty or whitespace");
        }
        if (string.IsNullOrWhiteSpace(profile.UserName))
        {
            throw new ArgumentNullException(nameof(profile), "Profile UserName cannot be null, empty or whitespace");
        }

        var context = new SphDataContext();
        var usp     = await context.LoadOneAsync <UserProfile>(p => p.UserName == profile.UserName) ?? new UserProfile();

        usp.UserName    = profile.UserName;
        usp.FullName    = profile.FullName;
        usp.Designation = profile.Designation;
        usp.Department  = profile.Department;
        usp.Mobile      = profile.Mobile;
        usp.Telephone   = profile.Telephone;
        usp.Email       = profile.Email;
        usp.RoleTypes   = string.Join(",", profile.Roles);
        usp.StartModule = designation.StartModule;
        if (usp.IsNewItem)
        {
            usp.Id = profile.UserName.ToIdFormat();
        }

        using (var session = context.OpenSession())
        {
            session.Attach(usp);
            await session.SubmitChanges();
        }

        return(usp);
    }
Esempio n. 20
0
        public async Task <ActionResult> VerifyEmail(string id)
        {
            ViewBag.success = true;
            ViewBag.status  = "OK";
            var context = new SphDataContext();

            var setting = await context.LoadOneAsync <Setting>(x => x.Id == id);

            if (null == setting)
            {
                ViewBag.success = false;
                ViewBag.status  = "The link is invalid.";
                return(View());
            }

            if ((DateTime.Now - setting.CreatedDate).TotalHours > 3)
            {
                ViewBag.success = false;
                ViewBag.status  = "The link has expired.";
                return(View());
            }

            if (!setting.Key.Equals("VerifyEmail"))
            {
                ViewBag.success = false;
                ViewBag.status  = "The link is not associated with verify email.";
                return(View());
            }

            var username = Membership.GetUserNameByEmail(setting.UserName);

            if (null == username)
            {
                ViewBag.success = false;
                ViewBag.status  = $"Cannot find any user with email {setting.UserName}.";
                return(View());
            }

            // email address verification complete
            await SetVerifyEmailFlag(username);

            return(RedirectToAction("success", "ost-account", new { success = true, status = "OK", operation = "verify-email" }));
        }
Esempio n. 21
0
        public async Task <ActionResult> IndikatorUkbp(string id)
        {
            var context = new SphDataContext();

            var sesi = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var user = await context.LoadOneAsync <Pengguna>(x => x.MyKad == sesi.MyKad);

            var ujianTask          = context.LoadOneAsync <Ujian>(x => x.Id == sesi.NamaUjian);
            var permohonanTask     = context.LoadOneAsync <Permohonan>(x => x.PermohonanNo == sesi.NamaProgram);
            var querySkorUkbp      = context.CreateQueryable <SkorUkbp>().Where(x => x.Jantina == user.Jantina || x.Jantina == "NA");
            var scoreTask          = context.LoadAsync(querySkorUkbp, 1, 200);
            var recommendationTask = context.LoadAsync(context.CreateQueryable <UkbpRecommendation>(), 1, 200);
            await Task.WhenAll(ujianTask, permohonanTask, scoreTask, recommendationTask);

            var scores          = await scoreTask;
            var recommendations = await recommendationTask;


            if (null == sesi)
            {
                return(HttpNotFound("Cannot find SesiUjian " + id));
            }
            if (null == user)
            {
                return(HttpNotFound("Cannot find user with MyKad " + sesi.MyKad));
            }

            SesiUjian sesiA, sesiB;

            if (sesi.NamaUjian == "UKBP-A")
            {
                sesiA = sesi;
                sesiB = await context.LoadOneAsync <SesiUjian>(x => x.NamaUjian == "UKBP-B" && x.NamaProgram == sesi.NamaProgram && x.MyKad == sesi.MyKad);
            }
            else
            {
                sesiB = sesi;
                sesiA = await context.LoadOneAsync <SesiUjian>(x => x.NamaUjian == "UKBP-A" && x.NamaProgram == sesi.NamaProgram && x.MyKad == sesi.MyKad);
            }

            var vm = new UkbpTraitViewModel(sesiA, sesiB, scores.ItemCollection.ToArray(), recommendations.ItemCollection.ToArray())
            {
                Permohonan = await permohonanTask,
                Ujian      = await ujianTask,
                Pengguna   = user
            };

            return(View("Indikator-UKBP", vm));
        }
Esempio n. 22
0
        public async Task <ActionResult> ResetPassword(string id, bool success = true, string status = "OK")
        {
            ViewBag.success = success;
            ViewBag.status  = status;

            var context = new SphDataContext();
            var setting = await context.LoadOneAsync <Setting>(x => x.Id == id);

            if (null == setting)
            {
                ViewBag.success = false;
                ViewBag.status  = "The link is invalid.";
                return(View());
            }

            if ((DateTime.Now - setting.CreatedDate).TotalHours > 3)
            {
                ViewBag.success = false;
                ViewBag.status  = "The link has expired.";
                return(View());
            }

            if (!setting.Key.Equals("ForgotPassword"))
            {
                ViewBag.success = false;
                ViewBag.status  = "The link is not associated with forgot password.";
                return(View());
            }

            var username = Membership.GetUserNameByEmail(setting.UserName);

            if (null == username)
            {
                ViewBag.success = false;
                ViewBag.status  = $"Cannot find any user with email {setting.UserName}.";
                return(View());
            }

            ViewBag.id    = id;
            ViewBag.email = setting.UserName;
            return(View());
        }
    public async Task <ActionResult> RemoveUser(string user)
    {
        var context = new SphDataContext();
        var profile = await context.LoadOneAsync <UserProfile>(x => x.UserName == user);

        if (null != profile)
        {
            using (var session = context.OpenSession())
            {
                session.Delete(profile);
                await session.SubmitChanges("Remove");
            }
        }
        var member = Membership.GetUser(user);

        if (null != member)
        {
            Membership.DeleteUser(user, true);
        }
        return(Content("{success : true, status : \"OK\"}", "application/json"));
    }
        public async Task <ActionResult> PrintIbkTrait(string id)
        {
            var context = new SphDataContext();
            var sesi    = await context.LoadOneAsync <SesiUjian>(x => x.Id == id);

            var user = await context.LoadOneAsync <Pengguna>(x => x.MyKad == sesi.MyKad);

            var ujian = await context.LoadOneAsync <Ujian>(x => x.Id == sesi.NamaUjian);

            var permohonan = await context.LoadOneAsync <Permohonan>(x => x.PermohonanNo == sesi.NamaProgram);

            if (null == sesi)
            {
                return(HttpNotFound("Cannot find SesiUjian " + id));
            }

            var vm = new IbkTraitViewModel(sesi)
            {
                Pengguna   = user,
                Ujian      = ujian,
                Permohonan = permohonan
            };


            var id1 = vm.KodKerjaya.Replace("/", "-");;
            var id2 = id1.Substring(4, 3) + "-" + id1.Substring(0, 3);


            //  if(vm.KodKerjaya != "xxx")
            //    throw new Exception("id1 = " + id1 + " and id2 = " + id2);

            vm.IbkRecommendation = await context.LoadOneAsync <IbkRecommendation>(
                x => x.Id == id1 || x.Id == id2);

            vm.IbkKodKerjaya = await context.LoadOneAsync <IbkKodKerjaya>(x => x.Id == vm.KodKerjaya.Substring(0, 1));


            var viewName = "Trait-Ibk";

            return(View(viewName, vm));
        }
Esempio n. 25
0
        public async Task <ActionResult> EstRegistration(string id, bool success = true, string status = "OK")
        {
            ViewBag.success = success;
            ViewBag.status  = status;

            var context = new SphDataContext();
            var setting = await context.LoadOneAsync <Setting>(x => x.Id == id);

            if (null == setting)
            {
                ViewBag.success = false;
                ViewBag.status  = "The link is invalid.";
                return(View());
            }

            if ((DateTime.Now - setting.CreatedDate).TotalHours > 3)
            {
                ViewBag.success = false;
                ViewBag.status  = "The link has expired.";
                return(View());
            }

            if (!setting.Key.Equals("EstRegistration"))
            {
                ViewBag.success = false;
                ViewBag.status  = "The link is not associated with EST Registration Form.";
                return(View());
            }

            var logger = ObjectBuilder.GetObject <ILogger>();

            var directory    = ObjectBuilder.GetObject <IDirectoryService>();
            var tempUsername = "******";
            var tempPassword = "******";

            if (await directory.AuthenticateAsync(tempUsername, tempPassword))
            {
                var identity = new ClaimsIdentity(ConfigurationManager.ApplicationName + "Cookie");
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, tempUsername));
                identity.AddClaim(new Claim(ClaimTypes.Name, tempUsername));
                var roles = Roles.GetRolesForUser(tempUsername).Select(x => new Claim(ClaimTypes.Role, x));
                identity.AddClaims(roles);

                var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == tempUsername);

                await logger.LogAsync(new LogEntry { Log = EventLog.Security });

                if (null != profile)
                {
                    var claims = profile.GetClaims();
                    identity.AddClaims(claims);

                    HttpContext.GetOwinContext().Authentication.SignIn(identity);

                    if (!string.IsNullOrEmpty(profile.Designation))
                    {
                        if (profile.Designation.Equals("Contract customer registrar"))
                        {
                            return(Redirect($"/ost#est-registration-form/0/sid/{setting.Id}"));
                        }
                    }
                    return(Redirect("/"));
                }
            }
            return(Redirect("/"));
        }
Esempio n. 26
0
        public async Task <ActionResult> ResetPassword(ResetPaswordModel model)
        {
            var context = new SphDataContext();
            var key     = await context.LoadOneAsync <Setting>(x => x.Id == model.Id);

            if (null == key)
            {
                return(HttpNotFound("Cannot find any password reset key " + model.Id));
            }

            var username = Membership.GetUserNameByEmail(model.Email);

            if (model.Password != model.ConfirmPassword)
            {
                return(Json(new { success = false, status = "PASSWORD_DOESNOT_MATCH", message = "Kata laluan anda tidak sama" }));
            }
            if (string.IsNullOrWhiteSpace(username))
            {
                return(HttpNotFound("Cannot find any user registered with " + model.Email));
            }

            var user = Membership.GetUser(username);

            if (null == user)
            {
                throw new Exception("Cannot find any user with email " + model.Email);
            }


            var ok = AdminController.CheckPasswordComplexity(Membership.Provider, model.Password);

            if (!ok)
            {
                return(Json(new { success = false, status = "PASSWORD_COMPLEXITY", message = "Kata laluan anda tidak mengikut kesesuaian yang ditetapkan" }));
            }

            var temp = user.ResetPassword();

            user.ChangePassword(temp, model.Password);

            var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == username)
                          ?? new UserProfile
            {
                UserName = username,
                Email    = model.Email,
                HasChangedDefaultPassword = true,
                Id          = username,
                StartModule = ""
            };

            profile.HasChangedDefaultPassword = true;

            using (var session = context.OpenSession())
            {
                session.Attach(profile);
                await session.SubmitChanges("Change password");
            }

            if (Request.ContentType.Contains("application/json"))
            {
                this.Response.ContentType = "application/json; charset=utf-8";
                return(Content(JsonConvert.SerializeObject(new { success = true, status = "OK" })));
            }

            return(Redirect("/"));
        }
Esempio n. 27
0
        public async Task <ActionResult> Login(OstLoginModel model, string returnUrl = "/")
        {
            if (string.IsNullOrEmpty(model.UserName))
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "Username cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Password))
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "Password cannot be set to null or empty." }));
            }

            var logger = ObjectBuilder.GetObject <ILogger>();

            var directory = ObjectBuilder.GetObject <IDirectoryService>();

            if (await directory.AuthenticateAsync(model.UserName, model.Password))
            {
                var identity = new ClaimsIdentity(ConfigurationManager.ApplicationName + "Cookie");
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Name, model.UserName));
                var roles = Roles.GetRolesForUser(model.UserName).Select(x => new Claim(ClaimTypes.Role, x));
                identity.AddClaims(roles);


                var context = new SphDataContext();
                var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == model.UserName);

                await logger.LogAsync(new LogEntry { Log = EventLog.Security });

                if (null != profile)
                {
                    // user email address verification pending
                    if (!profile.HasChangedDefaultPassword)
                    {
                        return(RedirectToAction("login", "ost-account", new { success = false, status = "Email verification pending. Please check your inbox for a verification email. You will be allowed to sign in after verification is complete." }));
                    }

                    var claims = profile.GetClaims();
                    identity.AddClaims(claims);

                    var designation = context.LoadOneFromSources <Designation>(x => x.Name == profile.Designation);
                    if (null != designation && designation.EnforceStartModule)
                    {
                        profile.StartModule = designation.StartModule;
                    }

                    HttpContext.GetOwinContext().Authentication.SignIn(identity);

                    if (!string.IsNullOrEmpty(profile.Designation))
                    {
                        if (profile.Designation.Equals("No contract customer") ||
                            profile.Designation.Equals("Contract customer"))
                        {
                            if (returnUrl == "/" ||
                                returnUrl.Equals("/ost", StringComparison.InvariantCultureIgnoreCase) ||
                                returnUrl.Equals("/ost#", StringComparison.InvariantCultureIgnoreCase) ||
                                returnUrl.Equals("/ost/", StringComparison.InvariantCultureIgnoreCase) ||
                                returnUrl.Equals("/ost/#", StringComparison.InvariantCultureIgnoreCase) ||
                                string.IsNullOrWhiteSpace(returnUrl))
                            {
                                return(Redirect("/ost#" + profile.StartModule));
                            }
                        }
                    }
                    return(Redirect("/sph"));
                }
                HttpContext.GetOwinContext().Authentication.SignIn(identity);
                if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
                return(RedirectToAction("Default", "OstHome"));
            }
            var user = await directory.GetUserAsync(model.UserName);

            await logger.LogAsync(new LogEntry { Log = EventLog.Security, Message = "Login Failed" });

            if (null != user && user.IsLockedOut)
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "Your acount has beeen locked, Please contact your administrator." }));
            }
            else
            {
                return(RedirectToAction("login", "ost-account", new { success = false, status = "The user name or password provided is incorrect." }));
            }
        }
Esempio n. 28
0
        public async Task <ActionResult> SocialMediaHandle(OstSocialModel model)
        {
            if (string.IsNullOrEmpty(model.Email))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Email cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Name))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Name cannot be set to null or empty." }));
            }
            if (string.IsNullOrEmpty(model.Id))
            {
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return(Json(new { success = false, status = "ERROR", message = "Id cannot be set to null or empty." }));
            }

            if (!string.IsNullOrEmpty(model.IdToken))
            {
                // TODO: Verify the integrity of the ID token
                // Phase 2
                if (model.Brand.Equals("facebook"))
                {
                }
                if (model.Brand.Equals("google"))
                {
                }
            }

            var username = Membership.GetUserNameByEmail(model.Email);

            if (null == username)
            {
                //register
                string strippedName = new string(model.Name.ToCharArray()
                                                 .Where(c => !char.IsWhiteSpace(c))
                                                 .ToArray()).ToLower();
                Random rnd         = new Random();
                int    rndTail     = rnd.Next(1000, 10000);
                var    newUserName = strippedName + rndTail.ToString();
                string password    = Membership.GeneratePassword(8, 1);

                var registerModel = new OstRegisterModel
                {
                    UserName        = newUserName,
                    FullName        = model.Name,
                    Email           = model.Email,
                    Password        = password,
                    ConfirmPassword = password,
                    Designation     = "No contract customer"
                };
                var result = await CreateAccount(registerModel);

                if (!result.Success)
                {
                    Response.StatusCode = (int)HttpStatusCode.Accepted;
                    return(Json(new { success = result.Success, status = "ERROR", message = result.Status }));
                }

                var emailModel = new OstCreateEmailModel
                {
                    UserEmail    = registerModel.Email,
                    UserName     = registerModel.UserName,
                    EmailSubject = "Verify your email address",
                    EmailBody    = $"To finish setting up this {ConfigurationManager.ApplicationFullName} account, we just need to make sure this email address is yours."
                };
                await SendVerificationEmail(emailModel);

                //create user details
                var context    = new SphDataContext();
                var userDetail = new Bespoke.Ost.UserDetails.Domain.UserDetail();
                var guid       = Guid.NewGuid().ToString();
                userDetail.Id     = guid;
                userDetail.UserId = registerModel.UserName;
                userDetail.Profile.ContactPerson            = registerModel.FullName;
                userDetail.ProfilePictureUrl                = model.PictureUrl;
                userDetail.Profile.ContactInformation.Email = registerModel.Email;
                userDetail.Profile.Address.Country          = "MY";
                using (var session = context.OpenSession())
                {
                    session.Attach(userDetail);
                    await session.SubmitChanges("Default");
                }

                Response.StatusCode = (int)HttpStatusCode.OK;
                return(Json(new { success = true, status = "OK", message = $"User {registerModel.UserName} with email {registerModel.Email} has been registered." }));
            }
            else
            {
                //login
                var logger   = ObjectBuilder.GetObject <ILogger>();
                var identity = new ClaimsIdentity(ConfigurationManager.ApplicationName + "Cookie");
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, username));
                identity.AddClaim(new Claim(ClaimTypes.Name, username));
                var roles = Roles.GetRolesForUser(username).Select(x => new Claim(ClaimTypes.Role, x));
                identity.AddClaims(roles);


                var context = new SphDataContext();
                var profile = await context.LoadOneAsync <UserProfile>(u => u.UserName == username);

                await logger.LogAsync(new LogEntry { Log = EventLog.Security });

                if (null != profile)
                {
                    // user email address verification pending
                    if (!profile.HasChangedDefaultPassword)
                    {
                        Response.StatusCode = (int)HttpStatusCode.Accepted;
                        return(Json(new { success = false, status = "ERROR", message = "Email verification pending. Please check your inbox for a verification email. You will be allowed to sign in after verification is complete." }));
                    }

                    var claims = profile.GetClaims();
                    identity.AddClaims(claims);

                    var designation = context.LoadOneFromSources <Designation>(x => x.Name == profile.Designation);
                    if (null != designation && designation.EnforceStartModule)
                    {
                        profile.StartModule = designation.StartModule;
                    }

                    HttpContext.GetOwinContext().Authentication.SignIn(identity);

                    Response.StatusCode = (int)HttpStatusCode.OK;
                    return(Json(new { success = true, status = "OK", message = $"User {profile.UserName} with email {profile.Email} has been authenticated." }));
                }
                HttpContext.GetOwinContext().Authentication.SignIn(identity);

                Response.StatusCode = (int)HttpStatusCode.OK;
                return(Json(new { success = true, status = "OK", message = $"User {profile.UserName} with email {profile.Email} has been authenticated." }));
            }
        }
    public async Task <IHttpActionResult> CreateToken([FromBody] GetTokenModel model)
    {
        if (model.grant_type == "password" && !Membership.ValidateUser(model.username, model.password))
        {
            return(Json(new { success = false, status = 403, message = "Cannot validate your username or password" }));
        }

        if (model.grant_type == "admin" && !User.IsInRole("administrators"))
        {
            return(Json(new { success = false, status = 403, message = "You are not in administrator role" }));
        }

        var ip = this.GetClientIp();

        if (model.grant_type == "local_network" && !ip.StartsWith("1"))
        {
            return(Json(new { success = false, status = 403, message = "local_network request must be done within specified IP address range " + ip }));
        }

        model.expiry = DateTime.Today.AddMonths(1);// give it 1 month validity
        var tokenService = ObjectBuilder.GetObject <ITokenService>();

        var context = new SphDataContext();
        var user    = await context.LoadOneAsync <UserProfile>(x => x.UserName == model.username);

        if (null == user)
        {
            user = new UserProfile
            {
                UserName    = model.username,
                Designation = "Device",
                HasChangedDefaultPassword = true,
                Email       = $"{model.username}@pos.com.my",
                Department  = "PPL",
                IsLockedOut = false
            };
            var profile = new Profile
            {
                UserName        = model.username,
                Password        = "******",
                ConfirmPassword = "******",
                Roles           = new[] { "devices" },
                Designation     = "Device",
                Email           = $"{model.username}@pos.com.my"
            };
            var ok = await AddUserAsync(profile).ConfigureAwait(false);

            if (!ok)
            {
                return(Invalid("Cannot create device with id " + model.username));
            }
        }

        // get existing token that still have at least 14 days validity
        var repos = ObjectBuilder.GetObject <ITokenRepository>();
        var lo    = await repos.LoadAsync(model.username, DateTime.Today.AddDays(14));

        var existing = lo.ItemCollection.LastOrDefault();

        if (null != existing)
        {
            var token1 = existing.GenerateToken();
            return(Json(existing.ToJson().Replace("\"WebId\"", $"\"token\":\"{token1}\",\r\n\"WebId\"")));
        }

        var roles = Roles.GetRolesForUser(model.username);
        var claim = await tokenService.CreateTokenAsync(user, roles, model.expiry);

        var token = claim.GenerateToken();
        var json  = claim.ToJson()
                    .Replace("\"WebId\"", $"\"token\":\"{token}\",\r\n\"WebId\"");

        return(Json(json));
    }
Esempio n. 30
0
        //exec:659b3c30-7a39-488e-da26-56b627c6050b
        public async Task <ActivityExecutionResult> Email2Async()
        {
            var result = new ActivityExecutionResult {
                Status = ActivityExecutionStatus.Success
            };
            var act = this.GetActivity <NotificationActivity>("659b3c30-7a39-488e-da26-56b627c6050b");

            result.NextActivities = new[] { "56dd17a3-d01d-44d6-a2c1-d1fb0587655e" };

            var @from = await this.TransformFromEmail2Async(act.From);

            var to = await this.TransformToEmail2Async(act.To);

            var subject = await this.TransformSubjectEmail2Async(act.Subject);

            var body = await this.TransformBodyEmail2Async(act.Body);

            var cc = await this.TransformBodyEmail2Async(act.Cc);

            var bcc = await this.TransformBodyEmail2Async(act.Bcc);

            var client = new System.Net.Mail.SmtpClient();
            var mm     = new System.Net.Mail.MailMessage();

            mm.Subject = subject;
            mm.Body    = body;
            mm.From    = new System.Net.Mail.MailAddress(@from);
            mm.To.Add(to);
            if (!string.IsNullOrWhiteSpace(cc))
            {
                mm.CC.Add(cc);
            }
            if (!string.IsNullOrWhiteSpace(bcc))
            {
                mm.Bcc.Add(bcc);
            }
            await client.SendMailAsync(mm).ConfigureAwait(false);


            var context = new SphDataContext();

            foreach (var et in to.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var et1  = et;
                var user = await context.LoadOneAsync <UserProfile>(u => u.Email == et1);

                if (null == user)
                {
                    continue;
                }
                var message = new Message
                {
                    Subject  = subject,
                    UserName = user.UserName,
                    Body     = body,
                    Id       = Strings.GenerateId()
                };
                using (var session = context.OpenSession())
                {
                    session.Attach(message);
                    await session.SubmitChanges("Email 2").ConfigureAwait(false);
                }
            }


            return(result);
        }