コード例 #1
0
        public static UserInfoDTO GetUserByID(int UserID)
        {
            UserInfoDTO user   = null;
            var         reader = SqlHelper.ExecuteReader(ConnectData.ConnectionString, "sp_GetUserByID", UserID);

            if (reader.HasRows)
            {
                user = new UserInfoDTO();
                while (reader.Read())
                {
                    var data = new UserInfoDTO()
                    {
                        UserID         = Convert.ToInt16(reader["UserID"]),
                        Username       = reader["Username"].ToString(),
                        Password       = reader["Password"].ToString(),
                        Fullname       = reader["FullName"].ToString(),
                        Phone          = reader["Phone"].ToString(),
                        Address        = reader["Address"].ToString(),
                        Status         = Convert.ToInt16(reader["Status"]),
                        CreateBy       = reader["CreateBy"].ToString(),
                        CreateDate     = Convert.ToDateTime(reader["CreateDate"]),
                        UpdateBy       = reader["UpdateBy"].ToString(),
                        LastUpdateDate = Convert.ToDateTime(reader["LastUpdateDate"]),
                        RoleID         = Convert.ToInt16(reader["RoleID"]),
                    };
                    user = data;
                }
                return(user);
            }
            return(null);
        }
コード例 #2
0
        public async Task <ServiceResponse <UserInfoDTO> > GetUserInfo(long userid)
        {
            ServiceResponse <UserInfoDTO> response = new ServiceResponse <UserInfoDTO>();

            try
            {
                UserInfo userInfo = await _context.UserInfo.FirstOrDefaultAsync
                                        (x => x.UserId == userid);

                UserInfoDTO ud = new UserInfoDTO();
                ud.UserId           = userInfo.UserId;
                ud.UserCat          = userInfo.UserCat;
                ud.SaleMedium       = userInfo.SaleMedium;
                ud.MonthlyShipments = userInfo.MonthlyShipments;
                ud.ProductCategory  = userInfo.ProductCategory;
                ud.OtherCategory    = userInfo.OtherCategory;
                //ud.createdDateTime = userInfo.CreatedDateTime;
                //       ud.UpdatedDateTime = userInfo.UpdatedDateTime;
                //         ud.IsComplete = userInfo.IsComplete;
                response.Data         = ud;
                response.Message      = "";
                response.Success      = true;
                response.ResponseCode = 301;
            }
            catch (Exception ex)
            {
                response.ResponseCode = 301;
                response.Message      = ex.Message;
                response.Success      = false;
            }
            return(response);
        }
コード例 #3
0
        public ActionResult CreateUser(UserInfoDTO user, int roleID)
        {
            if (CheckRole(1) == -1 && CheckRole(2) == -1)
            {
                if (CheckRole(1) == 0 && CheckRole(2) == 0)
                {
                    return(RedirectToAction("Login", "Home", new { area = "" }));
                }
                return(RedirectToAction("ErrorView", "Home", new { area = "" }));
            }
            var us = (Users)Session["User"];

            user.CreateBy       = us.Username;
            user.CreateDate     = DateTime.Now;
            user.UpdateBy       = "";
            user.LastUpdateDate = DateTime.Now;
            user.Status         = 1;
            if (user.ManageBy == null)
            {
                user.ManageBy = us.Username;
            }
            var rs = AdminService.CreateUser(user, roleID);

            return(Json(new { success = true }));
        }
コード例 #4
0
ファイル: UserController.cs プロジェクト: ANDRmark/project10
        public IHttpActionResult UpdateUser([FromBody] UpdateUserBindingModel model)
        {
            if (ModelState.IsValid)
            {
                UserInfoDTO user = this.userInfoService.GetById(model.Id);
                if (user == null)
                {
                    return(BadRequest("User not found"));
                }

                user.UserName = model.UserName;
                user.Email    = model.Email;

                user.Roles = new List <RoleDTO>();
                foreach (var role in model.Roles)
                {
                    user.Roles.Add(new RoleDTO()
                    {
                        Name = role.Name
                    });
                }
                this.userInfoService.Update(user);

                return(Ok());
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
コード例 #5
0
ファイル: RoleStrategyFactory.cs プロジェクト: gyb333/OLAP
        public static IRoleStrategy GetRoleStrategy(UserInfoDTO userInfo)
        {
            IRoleStrategy strategy = null;

            switch (userInfo.UserType)
            {
            case 12:     //KBP管理员
                strategy = new KBPAdminStrategy(RoleType.KBPAdmin, userInfo);
                break;

            case 161:       //营销公司职员
                strategy = new KBPUserStrategy(RoleType.KBPUser, userInfo);
                break;

            case 13:     //KDS经销商管理员
                strategy = new KDSAdminStrategy(RoleType.KDSAdmin, userInfo);
                break;

            case 14:        //KDS业务员权限
                strategy = new KDSUserStrategy(RoleType.KDSUser, userInfo);
                break;

            default:
                strategy = new NullStrategy();
                break;
            }
            return(strategy);
        }
コード例 #6
0
        //public ActionResult DeviceDetail(int id)
        //{

        //    DeviceViewModel device = AdminService.GetDeviceByID(id);
        //    return View(device);
        //}
        public ActionResult Detail(int id)
        {
            if (CheckRole(2) != 1)
            {
                if (CheckRole(2) == 0)
                {
                    return(RedirectToAction("Login", "Home", new { area = "" }));
                }
                return(RedirectToAction("ErrorView", "Home", new { area = "" }));
            }
            var user = (Users)Session["User"];

            if (TempData["EditResult"] != null)
            {
                ViewBag.EditResult = TempData["EditResult"];
            }
            UserInfoDTO us = new UserInfoDTO();

            us = AdminService.GetUserByID(id);
            if (us != null && us.ManageBy == user.Username || AdminService.CheckUserManage(id, user.Username))
            {
                return(View(us));
            }
            TempData["EditResult"] = 0;
            return(RedirectToAction("Customer", "Agency"));
        }
コード例 #7
0
        public ActionResult<UserInfoDTO> GetUserInfoAsync()
        {
            if (!User.Identity.IsAuthenticated)
                return Ok(new UserInfoDTO());

            var userInfo = new UserInfoDTO()
            {
                IsAuthenticated = User.Identity.IsAuthenticated
            };

            foreach (var claim in User.Claims)
            {
                switch (claim.Type)
                {
                    case ClaimTypes.NameIdentifier:
                        userInfo.UserId = ulong.Parse(claim.Value);
                        break;

                    case ClaimTypes.Name:
                        userInfo.Username = claim.Value;
                        break;

                    case DiscordAuthenticationConstants.Claims.AvatarHash:
                        userInfo.AvatarHash = claim.Value;
                        break;

                    case Constants.IsBotOwner:
                        userInfo.Claims.Add(claim.Type,claim.Value);
                        break;
                }
            }

            return Ok(userInfo);
        }
コード例 #8
0
    public UserInfoDTO QueryUserInfo(string userCode)
    {
        try
        {
            string sql = string.Format("select ID, Code, Name from Base_User where Code='{0}'", userCode);

            DataSet dataSet = SQLHelper.ExecuteDataSet(sql);
            if (dataSet == null || dataSet.Tables.Count == 0 || dataSet.Tables[0].Rows.Count == 0)
            {
                return(null);
            }
            DataRow dataRow = dataSet.Tables[0].Rows[0];

            UserInfoDTO userInfoDTO = new UserInfoDTO();
            userInfoDTO.UserID   = TypeHelper.ConvertType <long>(dataRow["ID"], 0);
            userInfoDTO.UserCode = TypeHelper.ConvertType <string>(dataRow["Code"], string.Empty);
            userInfoDTO.UserName = TypeHelper.ConvertType <string>(dataRow["Name"], string.Empty);

            return(userInfoDTO);
        }
        catch (Exception ex)
        {
            PDALog.Error(ex);
            throw ExceptionHelper.CreateSoapException(ex.Message, ex.Source);
        }
    }
コード例 #9
0
        private UserTokenDTO BuildToken(UserInfoDTO model, IList <string> roles)
        {
            var claims = new List <Claim>()
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, model.Email),
                new Claim(ClaimTypes.Name, model.Email),
                new Claim("myValue", "What I want"),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }
            var key                = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["jwt:key"]));
            var creds              = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var expiration         = DateTime.UtcNow.AddHours(1);
            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            return(new UserTokenDTO()
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expiration = expiration
            });
        }
        public ICollection <UserInfoDTO> GetUserFriends(UserInfoDTO dto)
        {
            var user = _userConverter.ToBusinessEntity(dto);
            var list = UserProvider.GetUserFriends(user);

            return(_userConverter.ToDataTransferEntityList(list));
        }
        public async Task <bool> DeleteUser(UserInfoDTO dto)
        {
            var user   = _userConverter.ToBusinessEntity(dto);
            var result = await UserProvider.DeleteUser(user);

            return(result.Succeeded);
        }
        public ICollection <ChatDTO> GetChatsOfUser(UserInfoDTO dto)
        {
            var user = _userConverter.ToBusinessEntity(dto);
            var list = UserProvider.GetChatsOfUser(user);

            return(_chatConverter.ToDataTransferEntityList(list));
        }
コード例 #13
0
        public ActionResult Register([Bind(Include = "Name,Password,ConfirmedPassword,Email,PhoneNumber,RoleName,Roles")] RegistrationViewModel registrationViewModel)
        {
            registrationViewModel.Roles = roleList.Roles;
            try
            {
                //registrationViewModel = RegisterationRoleMapper.Map<RolesDTO, RegistrationViewModel>(roleList);
                ModelState.Remove("Roles");
                if (ModelState.IsValid)
                {
                    UserRegisterDTO userRegisterDTO = RegistrationViewModelMapper.Map <RegistrationViewModel, UserRegisterDTO>(registrationViewModel);

                    UserInfoDTO newUserInfoDTO = userBusinessContext.RegisterUser(userRegisterDTO);
                    return(View("Success"));
                }
                else
                {
                    return(View(registrationViewModel));
                }
            }
            catch (EmailAlreadyExistsException ex)
            {
                ModelState.AddModelError("Email", "Email id already Registered");
                return(View(registrationViewModel));
            }
            catch (Exception ex)
            {
                return(RedirectToAction("ExceptionCatch", "Static", new { exception = ex.Message }));
            }
        }
コード例 #14
0
        public ActionResult <MessageModel <UserInfoDTO> > getOwnUserInfo()
        {
            UserInfoDTO userModel = null;

            //解JWT
            var identity = HttpContext.User.Identity as ClaimsIdentity;

            if (identity != null)
            {
                var userID = identity.FindFirst("id").Value;
                Console.WriteLine(identity.FindFirst("id").Value);
                UserInfoView userInfo = userService.GetUserInfoById(int.Parse(userID));
                if (userInfo == null)
                {
                    return(BadRequest(new MessageModel <UserInfoDTO>
                    {
                        Status = (int)HttpStatusCode.BadRequest,
                        Success = false,
                        Msg = "user does not exist!"
                    }));
                }

                // 將 user 置換成 ViewModel
                userModel = mapper.Map <UserInfoDTO>(userInfo);
            }
            return(new MessageModel <UserInfoDTO>
            {
                Data = userModel
            });
        }
コード例 #15
0
        public void updatePersonInfo(UserInfoDTO userInfo)
        {
            var person = mapper.Map <Person>(userInfo);

            service.Person.Update(person);
            service.Commit();
        }
コード例 #16
0
        /// <summary>
        /// Checks that EditUSer info seuccesfully edits a users info
        /// </summary>
        public void TestEditUserInfo()
        {
            //Arrange
            ClaimsIdentity objClaim = new ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, "3")
            });

            _userController.HttpContext.User = new ClaimsPrincipal(objClaim);
            EditUserDTO editUser = new EditUserDTO();

            editUser.FirstName          = "Bryan_Test";
            editUser.LastName           = "Ang_Test";
            editUser.DateOfBirth        = new DateTime(1984, 02, 09);
            editUser.PhoneNumber        = "5555555555";
            editUser.Email              = "*****@*****.**";
            editUser.MedicalInformation = "editing test";
            editUser.BankAccount        = "111-1111-1111111";

            //Act
            _ = _userController.EditUserInfo(editUser);
            var         response   = _userController.GetUserInfo();
            UserInfoDTO editedUser = response.Value;

            //Assert
            Assert.That(editedUser.FirstName == editUser.FirstName);
            Assert.That(editedUser.LastName == editUser.LastName);
            Assert.That(editedUser.DateOfBirth == editUser.DateOfBirth);
            Assert.That(editedUser.PhoneNumber == editUser.PhoneNumber);
            Assert.That(editedUser.Email == editUser.Email);
            Assert.That(editedUser.MedicalInformation == editUser.MedicalInformation);
            Assert.That(editedUser.BankAccount == editUser.BankAccount);
        }
コード例 #17
0
        public bool Register(string username, string password, UserInfoDTO userinfo, CardInfoDTO cardInfo, AdressDTO addres)
        {
            try
            {
                var acc = this._accountDal.CreateAccount(username, password);

                addres   = _adressDal.CreateAdress(addres);
                cardInfo = _cardinfoDal.CreateBankCardInfo(cardInfo);

                userinfo.UserID         = acc.UserID;
                userinfo.BankCardInfoID = (int)cardInfo.CardInfoID;
                userinfo.AdressID       = (int)addres.AdressID;

                this._userInfoDal.CreateUserInfo(userinfo);
                // transaction?
            }
            catch (Exception exp)
            {
                if (exp.Message == "User already exists!")
                {
                    return(false);
                }
                throw exp;
            }
            return(true);
        }
コード例 #18
0
        public async Task AddUserInfo(int userId, UserInfoDTO userInfo)
        {
            IMediaService media = new MediaService();

            var currentUrl = MediaPath.GetFolderPath(_unitOfWork.Users.Get(userId).Info.PhotoUrl);

            if (userInfo.Photo != null)
            {
                var url = await media.SavePersonImage(userInfo.Photo, userId, currentUrl);

                _unitOfWork.Users.Get(userId).Info.PhotoUrl = url;
            }
            else
            {
                //if (currentUrl != null)
                //{
                //    File.Delete(currentUrl);
                //}
            }
            //_unitOfWork.Users.Get(userId).Info.PhotoUrl = url;
            _unitOfWork.Users.Get(userId).Info.Address = userInfo.Address;
            _unitOfWork.Users.Get(userId).Info.About   = userInfo.About;
            _unitOfWork.Users.Get(userId).Info.SexId   = userInfo.Sex;
            _unitOfWork.Complete();
        }
コード例 #19
0
        public IHttpActionResult UpdateProfile(int id, [FromBody] UserInfoDTO dto)
        {
            Logger.log.Debug("at UserController.UpdateProfile");
            dto.Id = id;

            if (!this.CheckUserIdAcces(id))
            {
                Logger.log.Error("at UserController.UpdateProfile - User request denied");
                return(new Forbidden("User cannot modify other profile!"));
            }

            using (var client = SoapProvider.GetUserServiceClient())
            {
                try
                {
                    var result = client.UpdateUser(dto);
                    if (!result.Result)
                    {
                        Logger.log.Error("at UserController.UpdateProfile - " + result.Info);
                        return(BadRequest((string)result.Info));
                    }
                }
                catch (Exception ex)
                {
                    return(BadRequest(ex.ToString()));
                }
            }

            return(Ok());
        }
コード例 #20
0
        public async Task <IActionResult> ForgotPassword([FromBody] UserInfoDTO model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            ActionResult actionResult;
            var          user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
            {
                // Don't reveal that the user does not exist or is not confirmed
                ModelState.AddModelError(nameof(model.Email), "Invalid account.");
                actionResult = BadRequest(ModelState);
            }
            else
            {
                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                // var code = await _userManager.GeneratePasswordResetTokenAsync(user);
                //var callbackUrl = _urlHelper.ResetPasswordCallbackLink(_ravenDBIdUtil.GetUrlId(user.Id), code, _httpContextAccessor.HttpContext.Request.Scheme);
                //await _emailSender.SendPasswordForgetAsync(model.Email, user.UserName, callbackUrl);
                actionResult = Ok();
            }

            return(actionResult);
        }
コード例 #21
0
        private UserTokenDTO BuildToken(UserInfoDTO userInfo, string userid, IList <string> roles)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, userInfo.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.NameIdentifier, userid)
            };

            if (!(roles == null))
            {
                foreach (string role in roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }
            }
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            // Time expiration token. 30 minutes
            var expiration = DateTime.UtcNow.AddMinutes(30);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: null,
                audience: null,
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            return(new UserTokenDTO()
            {
                Token = new JwtSecurityTokenHandler().WriteToken(token),
                Expiration = expiration
            });
        }
コード例 #22
0
ファイル: UserInfoService.cs プロジェクト: lyc1359001996/btc
 /// <summary>
 /// 更新用户信息
 /// </summary>
 /// <param name="userInfo"></param>
 /// <returns></returns>
 public long UpdateUserInfo(UserInfoDTO userInfo)
 {
     using (B2CDbContext ctx = new B2CDbContext())
     {
         BaseService <UserInfoEntity> bs = new BaseService <UserInfoEntity>(ctx);
         var dbUser = bs.GetById(userInfo.Id);
         dbUser.Address      = userInfo.Address;
         dbUser.Email        = userInfo.Email;
         dbUser.Gender       = userInfo.Gender;
         dbUser.IDCardNo     = userInfo.IDCardNo;
         dbUser.Money        = userInfo.Money;
         dbUser.PassQuestion = userInfo.PassQuestion;
         dbUser.PassAnswer   = userInfo.PassAnswer;
         dbUser.PhoneNumber  = userInfo.PhoneNumber;
         dbUser.RoleInfoId   = userInfo.RoleId;
         dbUser.UserStateId  = userInfo.UserStateId;
         dbUser.UserName     = userInfo.UserName;
         string hash = CommomHelper.CalcMD5(dbUser.PassWordSalt + userInfo.Password);
         dbUser.PassWordHash = hash;
         dbUser.CardTypes.Clear();
         var atts = ctx.CardType.Where(a => a.IsDelete == false &&
                                       userInfo.CardTypeIds.Contains(a.Id));
         foreach (var item in atts)
         {
             dbUser.CardTypes.Add(item);
         }
         ctx.SaveChanges();
         return(dbUser.Id);
     }
 }
コード例 #23
0
        public async Task CreateWordFromMasterTable_根据母版Table生成Word_手动观察生成效果()
        {
            string curDir      = Environment.CurrentDirectory;
            string fileUrl     = Path.Combine(curDir, DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx");
            string templateurl = Path.Combine(curDir, "Resources", "UserMasterTable.docx");
            var    user1       = new UserInfoDTO()
            {
                Name    = "张三",
                Age     = 15,
                Gender  = "男",
                Remarks = "简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介"
            };
            var user2 = new UserInfoDTO()
            {
                Name    = "李四",
                Age     = 20,
                Gender  = "女",
                Remarks = "简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介简介"
            };

            var datas = new List <UserInfoDTO>()
            {
                user1, user2
            };

            for (int i = 0; i < 10; i++)
            {
                datas.Add(user1);
                datas.Add(user2);
            }

            var word = await _wordExportService.CreateFromMasterTableAsync(templateurl, datas);

            File.WriteAllBytes(fileUrl, word.WordBytes);
        }
コード例 #24
0
ファイル: UserInfoService.cs プロジェクト: lyc1359001996/btc
 /// <summary>
 /// 填写用户信息
 /// </summary>
 /// <param name="userInfo"></param>
 /// <returns></returns>
 public long AddUserInfo(UserInfoDTO userInfo)
 {
     using (B2CDbContext ctx = new B2CDbContext())
     {
         BaseService <CardTypeEntity> cardType
             = new BaseService <CardTypeEntity>(ctx);
         UserInfoEntity userInfoEntity = new UserInfoEntity();
         userInfoEntity.Address      = userInfo.Address;
         userInfoEntity.Email        = userInfo.Email;
         userInfoEntity.Gender       = userInfo.Gender;
         userInfoEntity.IDCardNo     = userInfo.IDCardNo;
         userInfoEntity.Money        = userInfo.Money;
         userInfoEntity.PassAnswer   = userInfo.PassAnswer;
         userInfoEntity.PassQuestion = userInfo.PassQuestion;
         string salt = CommomHelper.CreateVerifyCode(5);
         string hash = CommomHelper.CalcMD5(salt + userInfo.Password);
         userInfoEntity.PassWordSalt = salt;
         userInfoEntity.PassWordHash = hash;
         userInfoEntity.PhoneNumber  = userInfo.PhoneNumber;
         userInfoEntity.RoleInfoId   = userInfo.RoleId;
         userInfoEntity.UserName     = userInfo.UserName;
         userInfoEntity.UserStateId  = userInfo.UserStateId;
         foreach (var item in cardType.GetAll().Where(a => userInfo.CardTypeIds.Contains(a.Id)))
         {
             userInfoEntity.CardTypes.Add(item);
         }
         ctx.UserInfos.Add(userInfoEntity);
         ctx.SaveChanges();
         return(userInfoEntity.Id);
     }
 }
コード例 #25
0
        public async Task <Result <UserInfoDTO> > UpdateUserInfo(string userId, UserInfoDTO userInfoDTO)
        {
            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(Result <UserInfoDTO> .CreateFailed(
                           HttpStatusCode.NotFound, "User not found"));
            }
            user.PhoneNumber = userInfoDTO.PhoneNumber;
            user.Email       = userInfoDTO.Email;
            user.UserName    = userInfoDTO.Email;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception)
            {
                return(Result <UserInfoDTO> .CreateFailed(
                           HttpStatusCode.NotFound, "Error Changes are not saved"));;
            }

            return(Result <UserInfoDTO> .CreateSuccessful(new UserInfoDTO(user)));
        }
コード例 #26
0
        public async Task <UserInfoDTO> GetUserInfo(string token, ClaimsPrincipal principal)
        {
            UserInfoDTO userInfo = null;
            HttpClient  client   = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.Replace("Bearer ", ""));
            HttpResponseMessage response = await client.GetAsync($"{this.AuthConfiguration.Authority}/userinfo");

            if (response.IsSuccessStatusCode)
            {
                userInfo = await response.Content.ReadAsAsync <UserInfoDTO>();
            }
            else if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
            {
                // Retry if TooManyRequests
                // https://auth0.com/docs/support/policies/rate-limit-policy
                await Task.Delay(2000);

                userInfo = await response.Content.ReadAsAsync <UserInfoDTO>();
            }

            // Add permissions and roles (Auth0)
            if ((userInfo != null) && (this.AuthConfiguration.AuthType == AuthConstants.Auth0))
            {
                // Configure a new rule in Auth0 in Auth Pipeline / Rules
                // https://oscarchelo.blogspot.com/2021/09/get-permissions-and-roles-with-auth0.html
                userInfo.Roles       = principal.Claims.Where(x => x.Type == $"{this.AuthConfiguration.Namespace}/roles")?.Select(x => x.Value).ToList();
                userInfo.Permissions = principal.Claims.Where(x => x.Type == $"{this.AuthConfiguration.Namespace}/permissions")?.Select(x => x.Value).ToList();
            }

            return(userInfo);
        }
コード例 #27
0
 public ActionResult Login([Bind(Include = "Email, Password")] LoginViewModel loginViewModel)
 {
     if (ModelState.IsValid)
     {
         UserLoginDTO loggedInUserCredentialsDTO = LoginMapper.Map <LoginViewModel, UserLoginDTO>(loginViewModel);
         try
         {
             UserInfoDTO loggedInUserInfoDTO = UserBusinessContextObject.LoginUser(loggedInUserCredentialsDTO);
             Session["UserID"] = loggedInUserInfoDTO.ID;
             return(RedirectToAction("Index", "Home"));
         }
         catch (InvalidLoginException ex)
         {
             ModelState.AddModelError("", "Invalid Login Credentials");
             return(View(loginViewModel));
         }
         catch (IncorrectPasswordException ex)
         {
             ModelState.AddModelError("", "Incorrect password");
             return(View(loginViewModel));
         }
         catch (Exception ex)
         {
             ModelState.AddModelError("", "Something Went wrong. Please Try again later");
             return(View("Error"));
         }
     }
     return(View(loginViewModel));
 }
コード例 #28
0
        public UserInfoDTO UserInfoMapping(UserInfoDTO userInfo)
        {
            var id         = userInfo.Id;
            var skillNames = service.Skills.GetByCondition(e => e.UserFKey == id).Select(x => x.SkillName);

            var projectIds     = service.Project.GetByCondition(e => e.UserKey == id).Select(x => x.ProjectKey);
            var projectProduct = service.ProjectProduct.GetAll();

            var list = new List <string>();

            var length  = projectProduct.Count();
            var length2 = projectIds.Count();

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length2; j++)
                {
                    if (projectProduct.ElementAt(i).ProjectKey == projectIds.ElementAt(j))
                    {
                        list.Add(projectProduct.ElementAt(i).ProjectName);
                    }
                }
            }

            userInfo.Skills          = skillNames;
            userInfo.CurrentProjects = list;
            return(userInfo);
        }
コード例 #29
0
 /// <summary>
 /// 返回登录结果拼接
 /// </summary>
 /// <param name="restring">返回数据Data</param>
 /// <param name="olap">前台传递参数</param>
 /// <param name="mess">返回查询结果消息成功消息,错误消息</param>
 /// <param name="n">返回查询结果状态</param>
 /// <param name="count">返回数据结果数量</param>
 /// <returns></returns>
 public string GetResultMessage(string restring, UserInfoDTO olap, string mess, int n, int count)
 {
     restring  = "{ \"data\":\"" + olap.token + "\","; //成功的得到的数据
     restring += "\"message\":\"" + mess + "\",";      //成功消息,错误消息
     restring += "\"resultCode\":" + n + "}";          //返回成功与否 成功给正整数 1,2,3 这样 错误给负数 -1 -2 -3
     return(restring);
 }
コード例 #30
0
        public static List <UserInfoDTO> GetListUser(int RoleID)
        {
            List <UserInfoDTO> lst = null;
            var reader             = SqlHelper.ExecuteReader(ConnectData.ConnectionString, "sp_GetListUser", RoleID);

            if (reader.HasRows)
            {
                lst = new List <UserInfoDTO>();

                while (reader.Read())
                {
                    var data = new UserInfoDTO()
                    {
                        UserID     = Convert.ToInt32(reader["UserID"]),
                        Username   = reader["Username"].ToString(),
                        Password   = reader["Password"].ToString(),
                        Fullname   = reader["Fullname"].ToString(),
                        Phone      = reader["Phone"].ToString(),
                        Status     = Convert.ToInt32(reader["Status"]),
                        CreateDate = Convert.ToDateTime(reader["CreateDate"]),
                    };
                    lst.Add(data);
                }
            }
            return(lst);
        }