Ejemplo n.º 1
0
        public CurrentUserModel ToCurrentUserModelFrom(UserTable from)
        {
            var user = new CurrentUserModel();

            user.Password = from.Password;

            user.Followers      = new List <UserModel> ();
            user.Following      = new List <UserModel> ();
            user.LikedPosts     = new List <LikedPhotoModel> ();
            user.SavedPosts     = new List <SavedPhotoModel> ();
            user.Posts          = new List <PostModel> ();
            user.FollowingPosts = new List <PostModel> ();

            user.Id        = from.Id;
            user.Email     = from.Email;
            user.FirstName = from.FirstName;
            user.LastName  = from.LastName;
            user.UserName  = user.UserName ?? user.FirstName + " " + user.LastName;
            user.Password  = from.Password;
            user.Avatar    = from.Avatar;
            user.Bio       = from.Bio;

            from.Followers?.ForEach(x => user.Followers?.Add(ToFollowerModel(x)));
            from.Following?.ForEach(x => user.Followers?.Add(ToFollowerModel(x)));
            from.Posts?.ForEach(x => user.Posts?.Add(ToPostModelFrom(x)));
            from.LikedPosts?.ForEach(x => user.LikedPosts?.Add(ToPostModelFrom(x)));
            from.SavedPosts?.ForEach(x => user.SavedPosts?.Add(ToPostModelFrom(x)));

            user.Following?.ForEach(u => user.FollowingPosts.AddRange(u.Posts));
            user.FollowingPosts?.OrderByDescending(post => post.DateCreated);

            return(user);
        }
Ejemplo n.º 2
0
        public async Task <DatabaseResponseWithoutData> UpdateCurrentUserAsync(CurrentUserModel user)
        {
            if (user != null)
            {
                if (!user.IsValid())
                {
                    string message = "";
                    user.GetErrorMessages().ForEach(error => message += error);

                    return(new DatabaseResponseWithoutData(false, message));
                }

                var currentUser = await _userRepository.GetUserAsync(user.Id);

                if (currentUser.Password != user.Password)
                {
                    user.Password = PasswordHashingHelper.HashPassword(user.Password);
                }

                var newUser = _databaseMapper.ToUserFrom(user);

                try {
                    await _userRepository.UpdateUserAsync(newUser);
                } catch (SQLiteException sqliteEx) {
                    return(new DatabaseResponseWithoutData(false, sqliteEx.Message));
                } catch (Exception ex) {
                    return(new DatabaseResponseWithoutData(false, ex.Message));
                }

                return(new DatabaseResponseWithoutData(true));
            }

            return(new DatabaseResponseWithoutData(false, ""));
        }
Ejemplo n.º 3
0
 public BaseDynamicParameters(CurrentUserModel currentUser)
 {
     if (currentUser != null)
     {
         base.Add("@i_ClientId", currentUser.ClientId);
     }
 }
Ejemplo n.º 4
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controllerName = filterContext.RouteData.Values["Controller"].ToString().ToLower();
            var actionName     = filterContext.RouteData.Values["Action"].ToString().ToLower();
            var user           = filterContext.HttpContext.User;
            var loginInfo      = filterContext.HttpContext.Request.Cookies["_formAuthInfo_"];

            //user.Identity.Name
            if (!controllerName.Equals("account"))
            {
                if (loginInfo == null)
                {
                    if (controllerName.Equals("home"))
                    {
                        base.OnActionExecuting(filterContext);
                    }
                    else
                    {
                        filterContext.Result = RedirectToAction("Login", "Account");
                    }
                }
                else
                {
                    var model = System.Web.Helpers.Json.Decode(loginInfo.Value, typeof(UserInfoModel));

                    CurrentUser = new CurrentUserModel()
                    {
                        UserName = model.Name,
                        UserId   = model.Id
                    };
                }
            }
            base.OnActionExecuting(filterContext);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// 设置当前线程用户
 /// </summary>
 /// <param name="user"></param>
 public static void SetCurrentUser(CurrentUserModel user)
 {
     if (user != null)
     {
         CallContext <CurrentUserModel> .SetData(CallContextType.User, user);
     }
 }
Ejemplo n.º 6
0
 public ActionResult RejectRelease(int id)
 {
     CurrentUserModel.CheckIsAdmin();
     CurrentUserModel.RejectRelease(id);
     BuildService.UpdateRepositories(false);
     return(View("Index"));
 }
Ejemplo n.º 7
0
        public ActionResult EditApplication(int id)
        {
            CurrentUserModel.CheckIsSiteAdmin();
            Application app = CurrentServiceModel.GetApplication(id);

            return(View("EditApplication", app));
        }
Ejemplo n.º 8
0
        public string GetToken(CurrentUserModel userModel)
        {
            //string jtiCustom = Guid.NewGuid().ToString();//用来标识 Token
            var claims = new[]
            {
                new Claim(ClaimTypes.Name, userModel.Name),
                new Claim("EMail", userModel.EMail),
                new Claim("Account", userModel.Account),
                new Claim("Age", userModel.Age.ToString()),
                new Claim("Id", userModel.Id.ToString()),
                new Claim("Mobile", userModel.Mobile),
                new Claim(ClaimTypes.Role, userModel.Role),
                //new Claim("Role", userModel.Role),//这个不能角色授权
                new Claim("Sex", userModel.Sex.ToString())   //各种信息拼装
            };

            string keyDir = Directory.GetCurrentDirectory();

            if (RSAHelper.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams) == false)
            {
                keyParams = RSAHelper.GenerateAndSaveKey(keyDir);
            }
            var credentials = new SigningCredentials(new RsaSecurityKey(keyParams), SecurityAlgorithms.RsaSha256Signature);

            var token = new JwtSecurityToken(
                issuer: this._JWTTokenOptions.Issuer,
                audience: this._JWTTokenOptions.Audience,
                claims: claims,
                expires: DateTime.Now.AddMinutes(60),//5分钟有效期
                signingCredentials: credentials);
            var    handler     = new JwtSecurityTokenHandler();
            string tokenString = handler.WriteToken(token);

            return(tokenString);
        }
Ejemplo n.º 9
0
        public string Login(string name, string password)
        {
            if ("System".Equals(name) && "zjzt#123456".Equals(password))//应该数据库
            {
                CurrentUserModel currentUser = new CurrentUserModel()
                {
                    Id      = 123,
                    Account = "*****@*****.**",
                    EMail   = "*****@*****.**",
                    Mobile  = "173****8159",
                    Sex     = 1,
                    Age     = 33,
                    Name    = "ZJZT",
                    Role    = "Admin"
                };

                string token = this._iJWTService.GetToken(currentUser);
                return(JsonConvert.SerializeObject(new
                {
                    result = true,
                    token
                }));
            }
            else
            {
                return(JsonConvert.SerializeObject(new
                {
                    result = false,
                    token = ""
                }));
            }
        }
Ejemplo n.º 10
0
        public string Login(string name, string password)
        {
            if ("Eleven".Equals(name) && "123456".Equals(password))//应该数据库
            {
                CurrentUserModel currentUser = new CurrentUserModel()
                {
                    Id      = 123,
                    Account = "*****@*****.**",
                    EMail   = "*****@*****.**",
                    Mobile  = "18664876671",
                    Sex     = 1,
                    Age     = 33,
                    Name    = "Eleven",
                    Role    = "Admin"
                };

                string token = this._iJWTService.GetToken(currentUser);
                return(JsonConvert.SerializeObject(new
                {
                    result = true,
                    token
                }));
            }
            else
            {
                return(JsonConvert.SerializeObject(new
                {
                    result = false,
                    token = ""
                }));
            }
        }
Ejemplo n.º 11
0
        public CurrentUserModel ToCurrentUserModelFrom(UserObject userObject)
        {
            var user = new CurrentUserModel();

            user.FirstName  = userObject.FirstName;
            user.LastName   = userObject.LastName;
            user.Bio        = userObject.Bio;
            user.Email      = userObject.Email;
            user.UserName   = userObject.UserName;
            user.Avatar     = userObject.Avatar;
            user.Followers  = userObject.Followers.Select(ToUserModelFrom).ToList();
            user.Following  = userObject.Following.Select(ToUserModelFrom).ToList();
            user.Posts      = userObject.PublishedPosts.Select(ToPostModelFrom).ToList();
            user.LikedPosts = userObject.LikedPosts.Select(ToLikedPhotoModelFrom).ToList();
            user.SavedPosts = userObject.SavedPosts.Select(ToSavedPhotoModelModelFrom).ToList();

            user.UserName = user.FirstName + " " + user.LastName;

            user.Following?.ForEach(following =>
                                    user.FollowingPosts.AddRange(following.Posts.OrderByDescending(post => post.DateCreated).Take(10)));
            user.FollowingPosts?.OrderByDescending(post => post.DateCreated);

            user.Password = userObject.Password;

            return(user);
        }
Ejemplo n.º 12
0
        public void Start(object hint = null)
        {
            var tcs = new TaskCompletionSource <CurrentUserModel> ();
            CurrentUserModel user = null;

            try {
                user = _userService.GetRealmLoggedInUser();
                //Task.Run ( async () =>
                //            tcs.SetResult ( await _userService.GetLoggedInUserAsync () ) );
                //user = tcs.Task.Result;
            } catch (Exception ex) {
            }


            CurrentUser.User = user;

            if (user == null)
            {
                ShowViewModel <LoginViewModel> ();
            }
            else
            {
                ShowViewModel <MainTabViewModel> ();
            }
        }
Ejemplo n.º 13
0
        public bool LogAction_LOGOUT(CurrentUserModel cuM, string clientIP)
        {
            try
            {
#warning do poprawy
                Account ac = logUnityOfWork.AccountRepo.GetById(cuM.AccountId);
                logUnityOfWork.AccountRepo.Attach(ref ac);
                AccountLog al = new AccountLog
                {
                    Account           = ac,
                    Action            = "Uzytkownik " + cuM.UserName + " wylogował się do konta z adresu " + clientIP,
                    ActionDescription = "Użytkownik wylogowal się pomyślnie o " + DateTime.Now,
                    ActionType        = ActionType.LogOut,
                    EndDate           = DateTime.Now,
                    StartDate         = DateTime.Now
                };

                logUnityOfWork.AccountLogRepo.Add(al);
                logUnityOfWork.UnityOfWork.SaveChanges();
                return(true);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                logUnityOfWork.UnityOfWork.Dispose();
            }
        }
 public IActionResult RequestToken([FromBody] RequestTokenApiModel model)
 {
     try {
         if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password))
         {
             throw new ArgumentException("Missing username or password");
         }
         var result = _signInMgr.VerifyUser(model.Username, model.Password);
         if (!result)
         {
             _log.LogDebug("User '{0}' login unsuccessful", model.Username);
             return(Unauthorized());
         }
         var token  = _config.Api.GenerateToken(model.Username, "default");
         var retval = new CurrentUserModel {
             Username = model.Username,
             Token    = token
         };
         _log.LogInformation("User '{0}' successfully logged in", model.Username);
         return(Accepted(retval));
     } catch (ArgumentException ex) {
         return(BadRequest(ex.Message));
     } catch (Exception ex) {
         _log.LogError(ex, ex.Message);
         return(StatusCode(500, ex.Message));
     }
 }
 public static void SetUser(CurrentUserModel user)
 {
     if (user != null)
     {
         SetSessionVariable("CurrentUser", user);
     }
 }
Ejemplo n.º 16
0
        public ActionResult DeleteUpload(int sourceId)
        {
            SourceTag st = CurrentUserModel.GetSourceTag(sourceId);

            CurrentUserModel.DeleteSourceTag(st);
            return(RedirectToAction("Index", new { id = st.ProjectId }));
        }
Ejemplo n.º 17
0
        public ActionResult SaveSettings(Settings s)
        {
            if (!Settings.Default.InitialConfiguration)
            {
                CurrentUserModel.CheckIsSiteAdmin();
            }

            Settings.Default.DataPath      = s.DataPath;
            Settings.Default.OperationMode = s.OperationMode;
            Settings.Default.WebSiteHost   = s.WebSiteHost;
            Settings.Default.SmtpHost      = s.SmtpHost;
            Settings.Default.SmtpPassword  = s.SmtpPassword;
            Settings.Default.SmtpPort      = s.SmtpPort;
            Settings.Default.SmtpUser      = s.SmtpUser;
            Settings.Default.SmtpUseSSL    = s.SmtpUseSSL;

            CurrentUserModel.UpdateSettings(Settings.Default);

            Cydin.MvcApplication.UpdateRoutes();
            if (!CurrentServiceModel.ThereIsAdministrator())
            {
                return(Redirect(ControllerHelper.GetActionUrl("home", "Login", "User")));
            }
            else
            {
                CurrentServiceModel.EndInitialConfiguration();
                return(Redirect(ControllerHelper.GetActionUrl("home", null, null)));
            }
        }
Ejemplo n.º 18
0
        public ActionResult DeleteRelease(int releaseId)
        {
            Release r = CurrentUserModel.GetRelease(releaseId);

            CurrentUserModel.DeleteRelease(r);
            return(RedirectToAction("Index", new { id = r.ProjectId }));
        }
Ejemplo n.º 19
0
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                Account ac = accountService.GetUserByName(model.UserName);
                if (ac != null)
                {
                    CurrentUserModel cr = accountService.MapAccount(ac);
                    CurrentUser     = cr;
                    CurrenrUserName = cr.UserName;
                    string clientIP = Request.ServerVariables["REMOTE_ADDR"];
                    accountService.LogAction_LOGIN(ac, clientIP);

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "User"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Hasło lub login jest nieprawidłowe. Spróbuj ponownie.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 20
0
        public async Task <CurrentUserModel> CurrentUserAsync()
        {
            var result = new CurrentUserModel();

            var claimsPrincipal = _httpContextAccessor.HttpContext.User;

            if (claimsPrincipal.Identity.IsAuthenticated)
            {
                var identityUserId = _httpContextAccessor.HttpContext.User.Identities.First().Claims
                                     .FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;

                if (!string.IsNullOrEmpty(identityUserId))
                {
                    var user = await _dbContext.Users.FirstOrDefaultAsync(x => x.IdentityUserId == identityUserId);

                    if (user != null)
                    {
                        result = new CurrentUserModel
                        {
                            Id              = user.Id,
                            IdentityUserId  = user.IdentityUserId,
                            Email           = user.Email,
                            DisplayName     = user.DisplayName,
                            GravatarHash    = _gravatarService.HashEmailForGravatar(user.Email),
                            IsSuspended     = user.Status == UserStatusType.Suspended,
                            IsAuthenticated = true
                        };
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 21
0
        public bool Update(int id, ProductModel entity, CurrentUserModel currentUser)
        {
            try
            {
                CustomDynamicParameters parameters = new CustomDynamicParameters(currentUser);
                parameters.Add("@i_Id", id);
                parameters.Add("@i_Name", entity.Name);
                parameters.Add("@i_Description", entity.Description);
                parameters.Add("@i_Image", entity.Image);
                parameters.Add("@i_Price", entity.Price);
                parameters.Add("@i_Deposit", entity.Deposit);
                parameters.Add("@i_AvailableFromDate", entity.AvailableFromDate);
                parameters.Add("@i_AvailableToDate", entity.AvailableToDate);
                parameters.Add("@i_Location", entity.LocationId);
                parameters.Add("@i_Shipping", entity.Shipping);
                parameters.Add("@i_Address", entity.Address);

                ExecuteNoneQuery("Update_Product", parameters);
                return(true);
            }
            catch (Exception ex)
            {
                LogManager.LogError("Update Product: ", ex);
                throw ex;
            }
        }
Ejemplo n.º 22
0
        public ActionResult ReleasePackageInstaller(int id)
        {
            Release      rel = CurrentUserModel.GetRelease(id);
            StringWriter sw  = new StringWriter();

            BuildService.GenerateInstallerXml(sw, CurrentUserModel, rel, rel.PlatformsList);
            return(File(Encoding.UTF8.GetBytes(sw.ToString()), "application/x-" + CurrentUserModel.CurrentApplication.AddinPackageSubextension + "-mpack", rel.AddinId + "-" + rel.Version + CurrentUserModel.CurrentApplication.AddinPackageExtension));
        }
Ejemplo n.º 23
0
        public ActionResult UpdateSource(int sourceTagId)
        {
            CurrentUserModel.CleanSources(sourceTagId);
            SourceTag st = CurrentUserModel.GetSourceTag(sourceTagId);

            BuildService.Build(CurrentUserModel.CurrentApplication.Id, st.ProjectId);
            return(RedirectToAction("Index", new { id = st.ProjectId }));
        }
Ejemplo n.º 24
0
        public List <NavigationItem> GetNavigationList(CurrentUserModel currentUser)
        {
            var result = ServiceHelper.CallService <List <NavigationItem> >(ServiceConst.CommonService.GetNavigationList,
                                                                            JsonConvert.SerializeObject(currentUser), this.CurrentUser.Token);
            var navigationList = result.Data;

            return(navigationList);
        }
Ejemplo n.º 25
0
        public ActionResult NewApplication()
        {
            CurrentUserModel.CheckIsSiteAdmin();
            Application app = new Application();

            app.Id = -1;
            return(View("EditApplication", app));
        }
        /// <summary>
        /// Get current logined user
        /// </summary>
        /// <returns></returns>
        /// CALL URL: _vti_bin/Services/Employee/EmployeeService.svc/GetCurrentUser
        public CurrentUserModel GetCurrentUser()
        {
            try
            {
                CurrentUserModel user = new CurrentUserModel();
                //Get Current Login User
                SPUser spUser = SPContext.Current.Web.CurrentUser;
                if (spUser.IsSiteAdmin)
                {
                    user.IsSystemAdmin = true;
                    //return user;
                }

                var          employeeDal     = new EmployeeInfoDAL(SPContext.Current.Web.Url);
                EmployeeInfo currentEmployee = HttpContext.Current.Session[StringConstant.SessionString.EmployeeLogedin] as EmployeeInfo;

                if (currentEmployee == null)
                {
                    if (spUser != null)
                    {
                        int currentLoginName = spUser.ID;
                        currentEmployee = employeeDal.GetByADAccount(currentLoginName);
                    }
                }

                if (currentEmployee != null)
                {
                    user = new CurrentUserModel()
                    {
                        ID               = currentEmployee.ID,
                        EmployeeID       = currentEmployee.EmployeeID,
                        Department       = LookupItemModel.ConvertFromEntity(currentEmployee.Department),
                        Location         = LookupItemModel.ConvertFromEntity(currentEmployee.FactoryLocation),
                        FullName         = currentEmployee.FullName,
                        EmployeePosition = (currentEmployee.EmployeePosition != null && currentEmployee.EmployeePosition.LookupId > 0) ? currentEmployee.EmployeePosition.LookupId : 0
                    };
                    if (user.Department != null && user.Department.LookupId > 0)
                    {
                        var departmentDetail = _departmentDAL.GetByID(user.Department.LookupId);
                        if (departmentDetail != null)
                        {
                            user.IsBODApprovalRequired = departmentDetail.IsBODApprovalRequired;
                        }
                    }
                }
                return(user);
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0,
                                                      new SPDiagnosticsCategory("STADA - Employee Service - GetCurrentUser fn",
                                                                                TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected,
                                                      string.Format(CultureInfo.InvariantCulture, "{0}:{1}", ex.Message, ex.StackTrace));
                return(null);
            }
        }
Ejemplo n.º 27
0
        //
        // GET: /Project/

        public ActionResult Index(int id)
        {
            Project p = CurrentUserModel.GetProject(id);

            if (p == null)
            {
                throw new Exception("Project not found");
            }
            return(View(p));
        }
Ejemplo n.º 28
0
        public virtual ActionResult ChangeHub(CurrentUserModel currentUser)
        {
            var user = _userProfileService.GetUser(User.Identity.Name);

            _userHubService.ChangeHub(user.UserProfileID, currentUser.DefaultHubId);

            //return RedirectToAction("Index", "Dispatch");
            //return Json(new { success = true });
            return(Request.UrlReferrer != null?Redirect(Request.UrlReferrer.PathAndQuery) : null);
        }
 public CurrentUserModel GetCurrentUser()
 {
     try
     {
         return(CurrentUserModel.FromJson(HTMLGet($"{_baseURL}api/currentuser")));
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Ejemplo n.º 30
0
        public ActionResult SetNotification(int id, string notif, string value)
        {
            if (!notif.StartsWith("notify-"))
            {
                return(Content("Unknown notification"));
            }
            ProjectNotification pnot = (ProjectNotification)Enum.Parse(typeof(ProjectNotification), notif.Substring(7));

            CurrentUserModel.SetProjectNotification(pnot, id, value == "true");
            return(Content("OK"));
        }