Пример #1
0
        public async Task <IActionResult> LogOut()
        {
            await SignInMgr.SignOutAsync();

            HttpContext.Response.Cookies.Delete("Identity.Domain");
            return(RedirectToAction("Index"));
        }
Пример #2
0
        public async Task <IActionResult> Login(User model, string totalPrice)
        {
            result = await SignInMgr.PasswordSignInAsync(model.Email, model.Password, false, false);

            if (result.Succeeded && totalPrice != null)
            {
                currentUser = await UserMgr.FindByEmailAsync(model.Email);

                await ChangeToKeyCustomer(currentUser);

                IsKeyCustomer   = UserMgr.IsInRoleAsync(currentUser, "KeyCustomer");
                DiscountedPrice = Convert.ToDouble(totalPrice);

                if (IsKeyCustomer.Result == true)
                {
                    DiscountedPrice *= 0.9;

                    return(RedirectToAction("SelectPaymentAndDeliveryOption", "OrderConfirmation", new { totalPrice = DiscountedPrice.ToString(), keyCustomer = IsKeyCustomer.Result }));
                }

                return(RedirectToAction("SelectPaymentAndDeliveryOption", "OrderConfirmation", new { totalPrice, keyCustomer = IsKeyCustomer.Result }));
            }
            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Products"));
            }


            ModelState.AddModelError(string.Empty, "Invalid Login Attempt");


            return(View(model));
        }
Пример #3
0
        public async Task <IActionResult> GetToken([FromBody] AuthBindingModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await UserMgr.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var signInResult = await SignInMgr.CheckPasswordSignInAsync(user, model.Password.ToString(), false);

                    if (signInResult.Succeeded)
                    {
                        var roles = await UserMgr.GetRolesAsync(user);

                        return(generateToken(user, roles.FirstOrDefault()));
                    }
                    else
                    {
                        var err2 = new { status = "error", message = "Authentication Failed ! Check Email & Password" };
                        return(BadRequest(err2));
                    }
                }

                var err = new { status = "error", message = "Could not find a user for given Email!" };
                return(BadRequest(err));
            }

            return(BadRequest());
        }
Пример #4
0
        public async Task <IActionResult> Register([FromForm] RegisterVM registerVM)
        {
            var user = new UserModel()
            {
                Subscribed = true,
                UserName   = registerVM.UserName,
                Email      = registerVM.Email
            };

            var res = await UserMgr.CreateAsync(user, registerVM.Password);

            if (res.Succeeded)
            {
                await _email.Welcome(registerVM.Email);

                var curUser = await UserMgr.FindByNameAsync(user.UserName);

                var roleResult = UserMgr.AddToRoleAsync(curUser, "Visitor");
                roleResult.Wait();

                var signIn = await SignInMgr.PasswordSignInAsync(user.UserName, registerVM.Password, true, lockoutOnFailure : true);

                if (signIn.Succeeded)
                {
                    return(Redirect("/"));
                }
            }

            return(Redirect("/error"));
        }
Пример #5
0
        public async Task <Microsoft.AspNetCore.Identity.SignInResult> login([FromBody] JsonElement body)
        {
            Dictionary <string, string> json = JsonConvert.DeserializeObject <Dictionary <string, string> >(body.ToString());

            Microsoft.AspNetCore.Identity.SignInResult result = await SignInMgr.PasswordSignInAsync(json["email"], json["password"], true, false);

            return(result);
        }
Пример #6
0
        public async Task <IActionResult> Logout()
        {
            //var demo = User.FindFirstValue("RoleId");
            ////var listRole = RoleMgr.Roles.ToListAsync();
            //var demo1 = User.Claims.ToList();
            //HttpContext.Session.Clear();
            await SignInMgr.SignOutAsync();

            return(RedirectToAction("Index", "Login"));
        }
Пример #7
0
    public override void OnExit(params object[] argv)
    {
        GameObject nextLevelButton = argv[0] as GameObject;

        nextLevelButton.SetActive(false);
        int selectedDateTimeInt = XPlayerPrefs.GetInt(ChallengeController.selectedDateTimeStr);

        Debug.Log("sign:" + (selectedDateTimeInt - GameConfig.SignInDay).ToString());
        SignInMgr.GetInstance().Sign(selectedDateTimeInt - GameConfig.SignInDay);
    }
Пример #8
0
        public async Task <IActionResult> GenerateToken([FromBody] JWTViewModel m)
        {
            if (ModelState.IsValid)
            {
                AppUser user = await UserMgr.FindByNameAsync(m.UserName);

                if (user != null)
                {
                    var signInResult = await SignInMgr.CheckPasswordSignInAsync(user, m.Password.ToString(), false);

                    if (signInResult.Succeeded)
                    {
                        var key  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.JWT_Secret));
                        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, m.UserName),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim("UserType", user.Type),
                            new Claim("UserName", m.UserName)
                        };

                        var token = new JwtSecurityToken(

                            JWT.Iss,
                            JWT.Aud,
                            claims,
                            expires: DateTime.UtcNow.AddMinutes(30),
                            signingCredentials: cred

                            );

                        var results = new
                        {
                            token      = new JwtSecurityTokenHandler().WriteToken(token),
                            expiration = token.ValidTo
                        };
                        await LogChangeAsync(user, "Login");

                        return(Ok(results));
                    }
                    else
                    {
                        var err2 = new { status = "error", message = "Authentication Failed ! Check UserName & Password" };
                        return(BadRequest(err2));
                    }
                }

                var err = new { status = "error", message = "Could not find a user!" };
                return(BadRequest(err));
            }

            return(BadRequest());
        }
Пример #9
0
        public async Task <IActionResult> SignIn([FromForm] string username, [FromForm] string password)
        {
            var res = await SignInMgr.PasswordSignInAsync(username, password, true, lockoutOnFailure : true);

            if (res.Succeeded)
            {
                return(Redirect("/"));
            }

            return(Redirect("/signin/attempt"));
        }
Пример #10
0
        public async Task <IActionResult> Login(Staff obj)
        {
            var result = await SignInMgr.PasswordSignInAsync(obj.UserName, obj.PasswordHash, false, false);

            if (result.Succeeded)
            {
                //HttpContext.Session.SetString("Role", RoleMgr.FindByIdAsync(User.FindFirstValue("RoleId")).ToString());
                return(RedirectToAction("Index", "home"));
            }
            ViewData["Message"] = "Tài khoản hoặc mật khẩu không chính xát vui lòng đăng nhập lại";
            return(View());
        }
Пример #11
0
        public async Task <IActionResult> GenerateToken([FromBody] AuthBindingModel model)
        {
            if (ModelState.IsValid)
            {
                User user = await UserMgr.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var signInResult = await SignInMgr.CheckPasswordSignInAsync(user, model.Password.ToString(), false);

                    if (signInResult.Succeeded)
                    {
                        var key  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JWTSettings.Secret));
                        var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                        var claims = new[]
                        {
                            new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                            new Claim("UserType", ""),
                        };

                        var token = new JwtSecurityToken(

                            JWTSettings.Issuer,
                            JWTSettings.Audience,
                            claims,
                            expires: DateTime.UtcNow.AddMinutes(JWTSettings.ExpieryTimeInMins),
                            signingCredentials: cred

                            );

                        var results = new
                        {
                            thisuser   = new { UserName = user.UserName, Email = user.Email },
                            token      = new JwtSecurityTokenHandler().WriteToken(token),
                            expiration = token.ValidTo
                        };
                        return(Ok(results));
                    }
                    else
                    {
                        var err2 = new { status = "error", message = "Authentication Failed ! Check UserName & Password" };
                        return(BadRequest(err2));
                    }
                }

                var err = new { status = "error", message = "Could not find a user!" };
                return(BadRequest(err));
            }

            return(BadRequest());
        }
Пример #12
0
        public async Task <IActionResult> DeleteAccount()
        {
            // get current user
            var       username = User.Identity.Name.ToUpper();
            UserModel user     = UserMgr.Users.Where(x => x.NormalizedUserName == username).FirstOrDefault();

            // sign current user out and delete account
            await SignInMgr.SignOutAsync();

            await UserMgr.DeleteAsync(user);

            return(Redirect("/"));
        }
Пример #13
0
        public async Task <IActionResult> Index()
        {
            if (_helper.CorrectDomain())
            {
                if (HttpContext.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Request.Cookies["Identity.Domain"] != HttpContext.Items["domain"] as string)
                    {
                        return(RedirectToAction("LogOut"));
                    }
                    if (HttpContext.Items["domain"] as string == "default")
                    {
                        return(RedirectToAction("Index", "Admin"));
                    }
                    else
                    {
                        var idUser = _ut.GetUserId(HttpContext.User.Identity.Name);
                        _notificationTable.NotifyCloseDeadlineTasks(idUser);
                        if (idUser == 1)
                        {
                            _notificationTable.NotifyClosePaymentExpirationDate(_tt.GetTenantId(HttpContext.Items["domain"] as string));
                        }
                        var TenantPolicyResult = await _authorization.AuthorizeAsync(User, "TenantPolicy");

                        if (TenantPolicyResult.Succeeded)
                        {
                            return(RedirectToAction("Index", "HomePage"));
                        }
                        else
                        {
                            await SignInMgr.SignOutAsync();
                        }
                    }
                }
                var model = new IndexViewModel
                {
                    Domain         = HttpContext.Items["domain"] as string,
                    SignUpSelected = false,
                    SignIn         = new SignInForm(),
                    SignUp         = new SignUpForm()
                };
                return(View(model));
            }
            else
            {
                return(RedirectToAction("DomainError", "Home"));
            }
        }
Пример #14
0
        public async Task <IActionResult> Login()
        {
            var result = await SignInMgr.PasswordSignInAsync("TestUser", "test123", false, false);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ViewBag.Result = "result is: " + result.ToString();
            }



            return(View());
        }
Пример #15
0
    private void ModiMapAndInfo()
    {
        updateFlag = false;
        //修改图片和信息的显示
        //获得表
        int          dayId        = TimeUtil.getIntByDateTime(m_selectedDateTime);
        SignInConfig signInConfig = SignInMgr.GetInstance().GetConfigByID((uint)dayId);

        m_selectedLevelID = signInConfig.LevelId;
        LevelData   levelData   = LevelMgr.GetInstance().GetLevelConfig(m_selectedLevelID);
        LevelConfig levelConfig = levelData.Config;

        if (levelConfig == null)
        {
            Debug.LogError("获取不到关卡 " + m_selectedLevelID + " 的Config");
            return;
        }

        //TODO:修改mapIcon的图标,需要通过读表获取对应的图集
        AltasConfig altasConfig = AltasMgr.GetInstance().GetConfigByID(m_selectedLevelID);
        string      altasname   = altasConfig.AltasName2;
        UIAtlas     ats         = UIAtlasUtil.GetAtlas(altasname);

        if (ats != null)
        {
            ats.Sp = mapIcon;
            if (SignInMgr.GetInstance().IsSign(dayId - GameConfig.SignInDay))
            {
                ats.SetSprite("p_" + levelConfig.LevelPicture.ToString());
            }
            else
            {
                ats.SetSprite("s_" + levelConfig.LevelPicture.ToString());
            }
        }

        //TODO:修改info,包括了编号、名字、剩余时间和按钮的状态、文字等
        levelNumText.text = "#" + (SignInMgr.GetInstance().GetIndexByID((uint)dayId) + 1).ToString();
        LanguageMgr.GetInstance().GetLangStrByID(levelNameText, signInConfig.DailylevelName);

        StartCoroutine(TimeLeftUpdate(m_selectedDateTime.AddDays(1)));

        ModiTryButton();
    }
Пример #16
0
        public async Task <ActionResult <IdentityResult> > post([FromBody] JsonElement body)
        {
            Dictionary <string, string> json = JsonConvert.DeserializeObject <Dictionary <string, string> >(body.ToString());
            string password = json["password"];

            ApplicationUser appUser = new ApplicationUser(json["email"], json["firstName"], json["lastName"], json["email"]);
            IdentityResult  result;

            ApplicationUser user = await UserMgr.FindByNameAsync(appUser.Email);

            if (user == null)
            {
                //appUser.NormalizedUserName = appUser.Email;
                result = await UserMgr.CreateAsync(appUser, password);


                if (!result.Succeeded)
                {
                    return(result);
                }

                user = await UserMgr.FindByNameAsync(appUser.Email);

                //update
                user.UserName = json["userName"];
                context.UpdateUser(appUser);

                //emaim, password, mantiente login, bloqueo por x fallos
                await SignInMgr.PasswordSignInAsync(appUser.Email, password, true, false);

                return(result);
            }
            else
            {
                IdentityError error = new IdentityError();
                error.Code        = "10";
                error.Description = "Usuario existente";
                return(IdentityResult.Failed(error));
            }
        }
Пример #17
0
        public async Task <IActionResult> Register(User model, string totalPrice)
        {
            var user = new User {
                FirstName    = model.FirstName,
                LastName     = model.LastName,
                UserName     = model.Email,
                Email        = model.Email,
                City         = model.City,
                StreetAdress = model.StreetAdress,
                PostNumber   = model.PostNumber,
                CreatedAt    = DateTime.Now,
                PhoneNumber  = model.PhoneNumber,
                Currency     = model.Currency,
                Country      = model.Country
            };

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


            if (result.Succeeded && totalPrice != null)
            {
                await SignInMgr.SignInAsync(user, isPersistent : false);

                return(RedirectToAction("SelectPaymentAndDeliveryOption", "OrderConfirmation", new { totalPrice }));
            }
            if (result.Succeeded)
            {
                await SignInMgr.SignInAsync(user, isPersistent : false);

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

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error.Description);
            }

            return(View(model));
        }
Пример #18
0
        public async Task <IActionResult> SignIn(SignInForm signIn)
        {
            if (ModelState.IsValid)
            {
                if (HttpContext.Items["domain"] as string != "default")
                {
                    User user = await UserMgr.FindByEmailAsync(signIn.Email);

                    if (user != null)
                    {
                        var TenantPolicyResult = await _authorization.AuthorizeAsync(User, "TenantPolicy");

                        if (TenantPolicyResult.Succeeded)
                        {
                            var result = await SignInMgr.PasswordSignInAsync(user, signIn.Password, true, false);

                            if (result.Succeeded)
                            {
                                HttpContext.Response.Cookies.Append(
                                    "Identity.Domain",
                                    HttpContext.Items["domain"] as string,
                                    new CookieOptions {
                                    Expires  = DateTime.Now.AddDays(30),
                                    HttpOnly = true,
                                    Secure   = true,
                                    SameSite = SameSiteMode.Lax
                                }
                                    );

                                _notificationTable.NotifyCloseDeadlineTasks(user.Id);
                                if (user.Id == 1)
                                {
                                    _notificationTable.NotifyClosePaymentExpirationDate(_tt.GetTenantId(HttpContext.Items["domain"] as string));
                                }
                                return(RedirectToAction("Index", "HomePage"));
                            }
                            else
                            {
                                ModelState.AddModelError("CustomErr", $"Unable to login user {signIn.Email}.");
                            }
                        }
                        else
                        {
                            if (await UserMgr.IsInRoleAsync(user, nameof(Roles.DomainAdmin)))
                            {
                                var result = await SignInMgr.PasswordSignInAsync(user, signIn.Password, true, false);

                                if (result.Succeeded)
                                {
                                    HttpContext.Response.Cookies.Append(
                                        "Identity.Domain",
                                        HttpContext.Items["domain"] as string,
                                        new CookieOptions
                                    {
                                        Expires  = DateTime.Now.AddDays(30),
                                        HttpOnly = true,
                                        Secure   = true,
                                        SameSite = SameSiteMode.Lax
                                    }
                                        );
                                    return(RedirectToAction("Index", "Profile"));
                                }
                                else
                                {
                                    ModelState.AddModelError("CustomErr", $"Unable to login user {signIn.Email}.");
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("CustomErr", $"Service is not paid! Please contact your domain admin.");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("CustomErr", $"User {signIn.Email} does not exist in application.");
                    }
                }
                else
                {
                    GlobalUser user = await SharedUserMgr.FindByEmailAsync(signIn.Email);

                    if (user != null)
                    {
                        var result = await SharedSignInMgr.PasswordSignInAsync(user, signIn.Password, true, false);

                        if (result.Succeeded)
                        {
                            HttpContext.Response.Cookies.Append(
                                "Identity.Domain",
                                HttpContext.Items["domain"] as string,
                                new CookieOptions
                            {
                                Expires  = DateTime.Now.AddDays(30),
                                HttpOnly = true,
                                Secure   = true,
                                SameSite = SameSiteMode.Lax
                            }
                                );
                            return(RedirectToAction("Index", "Admin"));
                        }
                        else
                        {
                            ModelState.AddModelError("CustomErr", $"Unable to login user {signIn.Email}.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("CustomErr", $"User {signIn.Email} does not exist in application.");
                    }
                }
            }
            var model = new IndexViewModel
            {
                Domain         = HttpContext.Items["domain"] as string,
                SignUpSelected = false,
                SignIn         = signIn,
                SignUp         = new SignUpForm()
            };

            return(View("Index", model));
        }
Пример #19
0
        public async Task <IActionResult> Logout()
        {
            await SignInMgr.SignOutAsync();

            return(RedirectToAction("Index", "Products"));
        }
Пример #20
0
        public async Task <IActionResult> GoogleLoginCallback(string remoteError = null)
        {
            if (remoteError != null)
            {
                ModelState.AddModelError(string.Empty, $"Invalid Login Attempt: {remoteError}");
                return(RedirectToAction("Login"));
            }

            var info = await SignInMgr.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ModelState.AddModelError(string.Empty, "Error loading external login information.");
                return(RedirectToAction("Login"));
            }

            var googleEmail = info.Principal.FindFirstValue(ClaimTypes.Email);

            if (String.IsNullOrEmpty(googleEmail))
            {
                ModelState.AddModelError(string.Empty, "Could not find an email associated with your google account. Make sure your Google account has a registered email address.");
                return(RedirectToAction("Login"));
            }

            var matchingUser = Context.Users.Where(u => u.Email == googleEmail).FirstOrDefault();

            if (matchingUser != null && !Context.UserLogins.Where(u => u.UserId == matchingUser.Id).Any())
            {
                ModelState.AddModelError(string.Empty, "An account with that email address already exists.");
                return(RedirectToAction("Login"));
            }

            var result = await SignInMgr.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", "Products"));
            }

            var user = new User
            {
                Email         = googleEmail,
                UserName      = googleEmail,
                FirstName     = info.Principal.FindFirstValue(ClaimTypes.GivenName),
                LastName      = info.Principal.FindFirstValue(ClaimTypes.Surname),
                StreetAdress  = info.Principal.FindFirstValue(ClaimTypes.StreetAddress),
                PostNumber    = info.Principal.FindFirstValue(ClaimTypes.PostalCode),
                City          = info.Principal.FindFirstValue(ClaimTypes.Locality),
                Country       = info.Principal.FindFirstValue(ClaimTypes.Country),
                Currency      = "SEK",
                PhoneNumber   = info.Principal.FindFirstValue(ClaimTypes.MobilePhone),
                Password      = null,
                SecurityStamp = Guid.NewGuid().ToString()
            };
            await UserMgr.CreateAsync(user);

            await UserMgr.AddLoginAsync(user, info);

            await SignInMgr.SignInAsync(user, false);

            return(RedirectToAction("Index", "Products"));
        }
Пример #21
0
        public IActionResult GoogleLogin()
        {
            var properties = SignInMgr.ConfigureExternalAuthenticationProperties("Google", Url.Action("GoogleLoginCallback", "UserWithAuthentication"));

            return(new ChallengeResult("Google", properties));
        }
Пример #22
0
    public void InitDay(DateTime dateTime)
    {
        isLocked = false;
        isEmpty  = false;

        this.dateTime    = dateTime;
        this.dateTimeInt = TimeUtil.getIntByDateTime(dateTime);
        //TODO:首先获取配置表,如果今天没有配置任何信息,就不显示任何
        SignInConfig signInConfig = SignInMgr.GetInstance().GetConfigByID((uint)dateTimeInt);

        if (signInConfig == null || LevelMgr.GetInstance().GetLevelConfig(signInConfig.LevelId).Config == null)
        {
            // InitInvisible();
            dayBGSelectFinish.color   = Color.clear;
            dayBGSelectUnFinish.color = Color.clear;
            dayBGUnSelectFinish.color = Color.clear;
            lockImage.color           = Color.clear;
            dayText.text  = dateTime.Day.ToString();
            dayText.color = emptyColor;
            isEmpty       = true;

            return;
        }


        //TODO:和今天对比,如果是今天,字體显示为todaycolor;如果是今天之后,就先上锁,字體顯示爲lockcolor;如果是今天之前,就顯示爲normalcolor
        DateTime todayDateTime = DateTime.Today;

        dayBGSelectFinish.color   = Color.clear;
        dayBGSelectUnFinish.color = Color.clear;
        dayBGUnSelectFinish.color = Color.clear;
        dayText.text = dateTime.Day.ToString();


        bool todayOrPast = false;

        if (dateTime == todayDateTime)
        {
            dayText.color   = todayColor;
            lockImage.color = Color.clear;
            todayOrPast     = true;
        }
        else if (dateTime > todayDateTime)
        {
            dayText.color   = lockColor;
            lockImage.color = Color.white;
            isLocked        = true;
        }
        else
        {
            dayText.color   = normalColor;
            lockImage.color = Color.clear;
            todayOrPast     = true;
        }

        //如果是今天或者今天之前才要读取当天的完成状态
        if (todayOrPast)
        {
            //TODO:读取当天的完成状态 via 存档/如果存档中记录的是一系列二进制数,那么读取存档应该放在上层,获取当天的状态后,传入一个bool即可
            // int isChallengedInt = XPlayerPrefs.GetInt(TimeUtil.getIntByDateTime(dateTime) + challengeStr);

            //!just for test


            // Debug.Log(dateTime.ToShortDateString() + " " + dateTimeInt.ToString());
            // Debug.Log(GameConfig.SignInDay);

            // Debug.Log(dateTimeInt - GameConfig.SignInDay);

            isChallenged = SignInMgr.GetInstance().IsSign(dateTimeInt - GameConfig.SignInDay);

            //FINISH:判断当前日期是否被选中

            bool isSelected = XPlayerPrefs.GetInt(ChallengeController.selectedDateTimeStr) == dateTimeInt ? true : false;

            if (isChallenged && isSelected)
            {
                //如果當前日期是選中+完成
                dayBGSelectFinish.color = Color.white;
                dayText.color           = Color.white;
                //还要通知一下ChallengeController
                LogicEvent.Broadcast(LogicEvent.CALENDAR_SELECTED, dateTime, this.gameObject);
            }
            else if (!isChallenged && isSelected)
            {
                //如果當前日期是選中+未完成

                dayBGSelectUnFinish.color = Color.white;
                // Debug.Log("select unfinish:" + dateTime.ToShortDateString());
                // Debug.Log("select unfinish color?:" + dayBGSelectUnFinish.color.ToString());

                // Debug.Log("select finish color?:" + dayBGSelectFinish.color.ToString());
                LogicEvent.Broadcast(LogicEvent.CALENDAR_SELECTED, dateTime, this.gameObject);
            }
            else if (isChallenged && !isSelected)
            {
                //如果當前日期是未選中+完成
                dayBGUnSelectFinish.color = Color.white;
                dayText.color             = Color.white;
            }
        }
    }
Пример #23
0
    public void InitAllCalendars()
    {
        calendarList = new List <CalendarTest>();

        int selectedDateTimeInt = XPlayerPrefs.GetInt(ChallengeController.selectedDateTimeStr);

        Debug.Log("selectedDay:" + selectedDateTimeInt);

        if (selectedDateTimeInt != 0)
        {
            currentCalendarDateTime = TimeUtil.getDateTimeByInt(selectedDateTimeInt);
        }
        else
        {
            currentCalendarDateTime = DateTime.Today;

            X.Res.SignInConfig todaySignInConfig = SignInMgr.GetInstance().GetConfigByID((uint)TimeUtil.getIntByDateTime(currentCalendarDateTime));
            if (todaySignInConfig != null && LevelMgr.GetInstance().GetLevelConfig(todaySignInConfig.LevelId).Config != null)
            {
                XPlayerPrefs.SetInt(ChallengeController.selectedDateTimeStr, TimeUtil.getIntByDateTime(currentCalendarDateTime));
            }
            else
            {
                XPlayerPrefs.SetInt(ChallengeController.selectedDateTimeStr, (int)SignInMgr.GetInstance().MaxValidDay);
            }
        }

        selectedDateTimeInt = XPlayerPrefs.GetInt(ChallengeController.selectedDateTimeStr);
        Debug.Log("selectedDay:" + selectedDateTimeInt);



        int calendarCount  = transform.childCount;
        int centerCalendar = calendarCount / 2;
        int offsetMonth    = 0;


        for (int i = centerCalendar; i >= 0; i--)
        {
            Transform    calendarTrans = transform.GetChild(i);
            CalendarTest calendar      = calendarTrans.GetComponent <CalendarTest>();

            calendarList.Add(calendar);

            DateTime calendarDateTime = currentCalendarDateTime.AddMonths(offsetMonth);
            calendar.InitCalendar(calendarDateTime.Month, calendarDateTime.Year);
            offsetMonth--;
        }

        offsetMonth = 1;
        for (int i = centerCalendar + 1; i < calendarCount; i++)
        {
            Transform    calendarTrans = transform.GetChild(i);
            CalendarTest calendar      = calendarTrans.GetComponent <CalendarTest>();

            calendarList.Add(calendar);

            DateTime calendarDateTime = currentCalendarDateTime.AddMonths(offsetMonth);
            calendar.InitCalendar(calendarDateTime.Month, calendarDateTime.Year);
            offsetMonth++;
        }

        currentCalendarDateTime = new DateTime(currentCalendarDateTime.Year, currentCalendarDateTime.Month, 1);
        Debug.Log(currentCalendarDateTime.Year + " " + currentCalendarDateTime.Month + " " + currentCalendarDateTime.Day);
    }
Пример #24
0
        public async Task <IActionResult> LogOut()
        {
            await SignInMgr.SignOutAsync();

            return(Redirect("/"));
        }
Пример #25
0
        public async Task <IActionResult> SignUp(SignUpForm signUp)
        {
            if (HttpContext.Items["domain"] as string == "default")
            {
                if (!string.IsNullOrEmpty(signUp.TenantDomain) && !string.IsNullOrEmpty(signUp.TenantName) && ModelState.IsValid)
                {
                    if (Regex.Matches(signUp.TenantDomain, @"[a-zA-Z]").Count == signUp.TenantDomain.Length)
                    {
                        var blacklist = new string[] { "default", "admin", "NewTenantUser", "sa", "helper", "dbo", "guest", "sys", "ttask" };
                        if (!_tt.TenantAlreadyExists(signUp.TenantDomain) && !blacklist.Contains(signUp.TenantDomain))
                        {
                            _newTenant.NewTenant(signUp.TenantName, signUp.TenantDomain);
                            Directory.CreateDirectory(@"wwwroot/img/profile/" + signUp.TenantDomain);

                            HttpContext.Items["domain"] = signUp.TenantDomain;

                            int tenantId = _tt.GetTenantId(signUp.TenantDomain);


                            var user = new User()
                            {
                                Id          = 1,
                                UserName    = signUp.Email,
                                Email       = signUp.Email,
                                FirstName   = signUp.FirstName,
                                Surname     = signUp.Surname,
                                PhoneNumber = signUp.PhoneNumber,
                                IdTenant    = tenantId
                            };


                            HttpContext.Items["domain"] = signUp.TenantDomain;
                            IdentityResult result = await UserMgr.CreateAsync(user, signUp.Password);

                            if (result.Succeeded)
                            {
                                await UserMgr.AddToRolesAsync(user, new List <string> {
                                    nameof(Roles.NormalUser), nameof(Roles.DomainAdmin), nameof(Roles.Manager)
                                });

                                var settings = new UserSettings()
                                {
                                    Coloring      = "0",
                                    CustomizeView = "0",
                                    Notifications = "0",
                                    IdUser        = user.Id
                                };
                                _ut.InsertSettings(settings);


                                return(Redirect($"https://{HttpContext.Request.Host}/{signUp.TenantDomain}"));
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("CustomErr", $"Domain {signUp.TenantDomain} already exists.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("CustomErr", $"Domain has to contain letters only.");
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(signUp.TenantName))
                    {
                        ModelState.AddModelError("signUp.TenantName", "Company name is required field!");
                    }
                    if (string.IsNullOrEmpty(signUp.TenantDomain))
                    {
                        ModelState.AddModelError("signUp.TenantDomain", "Domain is required field!");
                    }
                }
            }
            else
            {
                var idService = _serviceOrderTable.GetInUseServiceIdByTenantId(_tt.GetTenantId(HttpContext.Items["domain"] as string));
                var noUsers   = _ut.GetNOUsers();

                if ((idService == (int)Services.Basic && noUsers < 5) || (idService == (int)Services.Pro && noUsers < 10) || idService == (int)Services.Business)
                {
                    if (ModelState.IsValid)
                    {
                        signUp.TenantDomain = HttpContext.Items["domain"] as string;

                        int tenantId = _tt.GetTenantId(signUp.TenantDomain);
                        int userId   = _ut.GetMaxId();


                        User user = await UserMgr.FindByEmailAsync(signUp.Email);

                        if (user == null)
                        {
                            user = new User()
                            {
                                Id          = userId,
                                UserName    = signUp.Email,
                                Email       = signUp.Email,
                                FirstName   = signUp.FirstName,
                                Surname     = signUp.Surname,
                                PhoneNumber = signUp.PhoneNumber,
                                IdTenant    = tenantId
                            };


                            IdentityResult result = await UserMgr.CreateAsync(user, signUp.Password);

                            if (result.Succeeded)
                            {
                                await UserMgr.AddToRoleAsync(user, nameof(Roles.NormalUser));

                                if (userId == 1)
                                {
                                    await UserMgr.AddToRoleAsync(user, nameof(Roles.DomainAdmin));

                                    await UserMgr.AddToRoleAsync(user, nameof(Roles.Manager));
                                }

                                var settings = new UserSettings()
                                {
                                    Coloring      = "0",
                                    CustomizeView = "0",
                                    Notifications = "0",
                                    IdUser        = user.Id
                                };
                                _ut.InsertSettings(settings);

                                var TenantPolicyResult = await _authorization.AuthorizeAsync(User, "TenantPolicy");

                                if (TenantPolicyResult.Succeeded)
                                {
                                    var msg = "User " + user.FirstName + " " + user.Surname + " has signed up in your application.";
                                    _notificationTable.NotifyUser(1, msg);
                                    var signInResult = await SignInMgr.PasswordSignInAsync(user, signUp.Password, false, false);

                                    if (signInResult.Succeeded)
                                    {
                                        HttpContext.Response.Cookies.Append(
                                            "Identity.Domain",
                                            HttpContext.Items["domain"] as string,
                                            new CookieOptions {
                                            Expires  = DateTime.Now.AddDays(30),
                                            HttpOnly = true,
                                            Secure   = true,
                                            SameSite = SameSiteMode.Lax
                                        }
                                            );
                                        return(RedirectToAction("Index", "HomePage"));
                                    }
                                }
                                else
                                {
                                    ModelState.AddModelError("CustomErr", $"User was created, but service of your domain is not paid. Sign in is impossible. Please contact your domain admin.");
                                }
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("CustomErr", $"User {user.Email} already exists.");
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("CustomErr", $"Number of users has been exceeded! If you want to register, contact domain admin to subscribe to higher service.");
                }
            }

            var model = new IndexViewModel
            {
                Domain         = HttpContext.Items["domain"] as string,
                SignUpSelected = true,
                SignIn         = new SignInForm(),
                SignUp         = signUp
            };

            return(View("Index", model));
        }
Пример #26
0
    public void ShowBesideMonthCalendar(bool nextOrLast)
    {
        if (nextOrLast)
        {
            //跳至下一个月
            DateTime nextCalendarDateTime = currentCalendarDateTime.AddMonths(1);
            DateTime firstDateOfNext      = new DateTime(nextCalendarDateTime.Year, nextCalendarDateTime.Month, 1);

            if (firstDateOfNext > TimeUtil.getDateTimeByInt((int)(SignInMgr.GetInstance().MaxDay)))
            {
                //如果下一個月的第一天沒有配置
                return;
            }

            //设置currentCalendarDateTime
            currentCalendarDateTime = currentCalendarDateTime.AddMonths(1);
            Debug.Log(currentCalendarDateTime.Year + " " + currentCalendarDateTime.Month + " " + currentCalendarDateTime.Day);
            nextCalendarDateTime = currentCalendarDateTime.AddMonths(1);


            //TODO:加入动画而非直接变换位置
            StartCoroutine(moveRectTrans(rectTrans, rectTrans.anchoredPosition + Vector2.left * panelWidth, 0.2f, () =>
            {
                // rectTrans.anchoredPosition = rectTrans.anchoredPosition + Vector2.left * panelWidth;

                //TODO:动画播完后,改变子节点的排序,即多个日历的排序,由于horizontalLayout的作用会改变每个日历的位置,将第一个日历放到最后时,当前展示的日历会往左移动,因此整个panel需要再往右移动

                //TODO:原本的第一个子节点,即第一个日历放到最后之后,将第一个日历变为当前查看的日历的下一月份的日历
                Transform firstCalendarTrans = rectTrans.GetChild(0);
                firstCalendarTrans.SetAsLastSibling();

                CalendarTest firstCalendar = firstCalendarTrans.GetComponent <CalendarTest>();

                firstCalendar.InitCalendar(nextCalendarDateTime.Month, nextCalendarDateTime.Year);

                Debug.Log("move back");
                rectTrans.anchoredPosition = rectTrans.anchoredPosition + Vector2.right * panelWidth;
            }));
        }
        else
        {
            //跳至上一个月
            DateTime lastCalendarDateTime = currentCalendarDateTime.AddMonths(-1);
            DateTime lastDateOfLast       = new DateTime(currentCalendarDateTime.Year, currentCalendarDateTime.Month, 1).AddDays(-1);
            if (lastDateOfLast < TimeUtil.getDateTimeByInt((int)(SignInMgr.GetInstance().MinDay)))
            {
                //如果上一個月的最後一天也沒有配置
                return;
            }

            //设置currentCalendarDateTime
            currentCalendarDateTime = currentCalendarDateTime.AddMonths(-1);
            Debug.Log(currentCalendarDateTime.Year + " " + currentCalendarDateTime.Month + " " + currentCalendarDateTime.Day);
            lastCalendarDateTime = currentCalendarDateTime.AddMonths(-1);

            //TODO:加入动画而非直接变换位置
            StartCoroutine(moveRectTrans(rectTrans, rectTrans.anchoredPosition + Vector2.right * panelWidth, 0.2f, () =>
            {
                //TODO:动画播完后,改变子节点的排序,即多个日历的排序,由于horizontalLayout的作用会改变每个日历的位置,将最后一个日历放到开头时,当前展示的日历会往右移动,因此整个panel需要再往左移动

                //TODO:原本的最后一个子节点,即最后一个日历放到开头之后,将最后一个日历变为当前查看的日历的前一月份的日历
                Transform lastCalendarTrans = rectTrans.GetChild(rectTrans.childCount - 1);
                lastCalendarTrans.SetAsFirstSibling();

                CalendarTest lastCalendar = lastCalendarTrans.GetComponent <CalendarTest>();
                lastCalendar.InitCalendar(lastCalendarDateTime.Month, lastCalendarDateTime.Year);

                rectTrans.anchoredPosition = rectTrans.anchoredPosition + Vector2.left * panelWidth;
            }));
            // rectTrans.anchoredPosition = rectTrans.anchoredPosition + Vector2.right * panelWidth;
        }
    }