Ejemplo n.º 1
0
 protected void Page_Load(object sender, EventArgs e)
 {
     //
     //txtUser.Text = strName;
     if (HttpContext.Current.Session["userActive"] != null)
     {
         UserApp user        = new UserApp();
         UserApp userFromBdd = new UserApp();
         user = (UserApp)HttpContext.Current.Session["userActive"];
         IActiveUser activeUser = new UserActiveServiceImpl();
         userFromBdd = activeUser.getActiveUserById(user.usuario);
         //userFromBdd.app_rol = 1;
         if (userFromBdd != null)
         {
             txtUser.Text          = userFromBdd.nombres + " " + userFromBdd.apellidos;
             Session["userActive"] = userFromBdd;
             id_app_role.Value     = Convert.ToString(userFromBdd.area);
             //((SiteMaster)this.Master).strName = txtUser;
             // Response.Redirect("~/BuscarProyectos.aspx", false);
         }
         else
         {
             string flag = "false";
             Response.Redirect("~/Login.aspx", false);
         }
     }
 }
Ejemplo n.º 2
0
        private UserApp buildUserFromRequest(AddUserRequest request, int HomeAddressId)
        {
            UserApp user = new UserApp();

            user.userName     = request.name;
            user.userEmail    = request.emailUser;
            user.userLastname = request.lastname;
            user.userNicname  = request.nickname;

            /*
             * En caso de no tener un número de documento de identificación
             * el sistema le asigna el número de consumidor final;
             */
            if (string.IsNullOrEmpty(request.numDocument))
            {
                user.userNumDocument = "9999999999";
            }
            else
            {
                user.userNumDocument = request.numDocument;
            }

            user.userPhone     = request.phone;
            user.userType      = request.type;
            user.Disability    = null;
            user.userPassword  = this.createTempPass();
            user.CreateAt      = DateTime.Now;
            user.ModifiedAt    = DateTime.Now;
            user.HomeAddressId = HomeAddressId;
            return(_userModelServices.save(user));
        }
Ejemplo n.º 3
0
        public IActionResult Login(UserLogin userLogin)
        {
            if (userLogin is null || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            UserApp userApp = UserAppRepository.Login(userLogin.Email, userLogin.Password);

            if (userApp is null)
            {
                return(new ForbidResult());
            }


            if (userApp.Blocked)
            {
                return(new ForbidResult());
            }


            string fullName = userApp.Firstname + ' ' + userApp.Lastname;

            return(Ok(new UserWithToken()
            {
                Id = userApp.Id,
                FullLastname = fullName,
                Role = userApp.IsAdmin,
                Token = TokenManager.GenerateJWT(userApp)
            }));
        }
Ejemplo n.º 4
0
        public void Execute(string invocableName)
        {
            string appName = UserApp.GetAppName();

            string content = new StringBuilder()
                             .AppendLine("using Coravel.Invocable;")
                             .AppendLine("using System.Threading.Tasks;")
                             .AppendLine()
                             .AppendLine($"namespace {appName}.Invocables")
                             .AppendLine("{")
                             .AppendLine($"    public class {invocableName} : IInvocable")
                             .AppendLine("    {")
                             .AppendLine($"        public {invocableName}()")
                             .AppendLine("        {")
                             .AppendLine("        }")
                             .AppendLine()
                             .AppendLine("        public Task Invoke()")
                             .AppendLine("        {")
                             .AppendLine("            // What is your invocable going to do?")
                             .AppendLine("        }")
                             .AppendLine("    }")
                             .AppendLine("}")
                             .ToString();

            Files.WriteFileIfNotCreatedYet(InvocablesPath, invocableName + ".cs", content);
        }
Ejemplo n.º 5
0
        private States checkStateOfUser(UserApp userFound)
        {
            States stateFound = new States();
            var    context    = _context;
            var    query      = from stOfUs in context.Set <StatesOfUser>().Where(s => s.UserAppId == userFound.UserAppId)
                                join st in context.Set <States>() on stOfUs.StatesId equals st.StatesId
                                select new { st };

            if (query.Count() == 0)
            {
                _logger.LogError("[USER NOT HAS STATE] nickname: " + userFound.userNicname);
                stateFound = null;
            }
            else if (query.Count() > 1)
            {
                _logger.LogError("[USER HAS MORE THAT ONE STATE] nickname: " + userFound.userNicname);
                stateFound = null;
            }
            else
            {
                stateFound.Keyword     = query.Single().st.Keyword;
                stateFound.Description = query.Single().st.Description;
            }


            return(stateFound);
        }
Ejemplo n.º 6
0
        public UserApp UserAppInsert(UserApp userApp)
        {
            try
            {
                if (_data.ExistsUserNumber(userApp))
                {
                    throw new ExceptionBusiness($"There is already a user with an identification number {userApp.IdentificationNumber}");
                }

                userApp.DateCreation = DateTime.Now;

                var userId = _data.Insert <int>(userApp);
                userApp.UserId = userId;

                return(userApp);
            }
            catch (DataErrorException ex)
            {
                Logger.ErrorFatal("UserAppInsert", ex);
                throw ex;
            }
            catch (ExceptionBusiness)
            {
                throw;
            }
            catch (Exception ex)
            {
                Logger.ErrorFatal("GetUserAppsFromFilter", ex);
                throw ex;
            }
        }
Ejemplo n.º 7
0
        public void Should_CreateMailsAndSend()
        {
            // Arrange
            var user1 = new UserApp()
            {
                Id    = "10",
                Email = "*****@*****.**",
            };
            var user2 = new UserApp()
            {
                Id    = "1",
                Email = "*****@*****.**",
            };

            var TaskArg = new TaskDTO()
            {
                ModeratorIDs = { "10" },
                ViewerIDs    = { "1" }
            };

            var repository = new Mock <IRepositoryAsync <UserApp> >();

            repository.Setup(u => u.GetItemAsync("10")).ReturnsAsync(user1);
            repository.Setup(u => u.GetItemAsync("1")).ReturnsAsync(user2);

            // Act
            var userservice = new UserService(_mapper, repository.Object);
            var service     = new NotificationService(userservice);

            // Assert
            Assert.Throws <System.Net.Mail.SmtpException>(() => service.CreateMailsAndSend(TaskArg));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Actualiza un usuario por id en la base de datos
        /// </summary>
        /// <param name="user">usuario a modificar</param>
        /// <param name="session">sesion del usuario</param>
        /// <returns>UserApp</returns>
        public async Task <UserApp> UserAppUpdate(UserApp user, UserSession session)
        {
            try
            {
                if (await _userAppData.ExistUserByUserName(user))
                {
                    var control = await _controlsLanguageData.ControlFindByKey("UserExistForName", 2, session.LanguageId);

                    throw control.CreateException(user.UserName);
                }

                var oldUser = await _userAppData.GetAsync(user.UserId);

                oldUser.UpdateDate         = DateTime.Now;
                oldUser.UserUpdateId       = session.Id;
                oldUser.UserDocument       = user.UserDocument;
                oldUser.UserDocumentTypeId = user.UserDocumentTypeId;
                oldUser.UserEmail          = user.UserEmail;
                oldUser.UserFirstName      = user.UserFirstName;
                oldUser.UserLastName       = user.UserLastName;

                await _userAppData.UpdateAsync(oldUser);

                return(oldUser);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task <UserApp> UpdateUser(UserApp user)
        {
            var ret = _context.Users.Update(user);
            await _context.SaveChangesAsync();

            return(ret.Entity);
        }
Ejemplo n.º 10
0
        public ResultClass <UserEntity> CheckLogin(string username, string password)
        {
            ResultClass <UserEntity> _ret = new ResultClass <UserEntity>();
            UserApp bll = new UserApp();

            try
            {
                _ret.ResultData = bll.CheckLogin(username, password);
                if (_ret.ResultData != null)
                {
                    _ret.Result = true;
                    #region 生成且保存用户票据
                    _ret.ErrorMessage = "20171225";                                   //System.DateTime.Now.ToString("yyyyMMddHHmmss");//把票据返回给前端
                    HttpContext.Current.Session[_ret.ErrorMessage] = _ret.ResultData; //保存票据信息
                    #endregion
                }
            }
            catch (Exception ex)
            {
                _ret.ErrorMessage = ex.Message;
            }
            finally
            {
                bll.Dispose();
            }
            return(_ret);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Inserta un usuario nuevo en la base de datos
        /// </summary>
        /// <param name="user">usuario a crear</param>
        /// <param name="session">sesion del usuario</param>
        /// <returns>UserApp</returns>
        public async Task <UserApp> UserAppInsert(UserApp user, UserSession session)
        {
            try
            {
                if (await _userAppData.ExistUserByUserName(user))
                {
                    var control = await _controlsLanguageData.ControlFindByKey("UserExistForName", 2, session.LanguageId);

                    throw control.CreateException(user.UserName);
                }

                user.CreationDate   = DateTime.Now;
                user.UserCreationId = session.Id;
                user.UpdateDate     = null;
                user.UserUpdateId   = null;

                Guid id = await _userAppData.InsertKeyAsync <Guid>(user);

                user.UserId = id;
                return(user);
            }
            catch (Exception)
            {
                throw;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 动态点赞通知
        /// </summary>
        /// <param name="userId">接收者(用户)的 userId</param>
        /// <param name="date">点赞时间,4小时制时间格式(支持+年月日)	例如:15:01,或:2019年10月1日 15:01</param>
        /// <param name="page"></param>
        public static CommonResult SendGoodNotice(string userId, string date, string page)
        {
            CommonResult result = new CommonResult();
            User         user   = new UserApp().GetUserById(userId);

            if (user != null && !string.IsNullOrEmpty(date))
            {
                MessageTemplates template = messageTemplatesService.GetByMessageType("RemarkNotice");

                if (!string.IsNullOrEmpty(template.WxAppletSubscribeTemplateId) && template.UseInWxApplet)
                {
                    MemberSubscribeMsg memberSubscribeMsg = memberSubscribeMsgService.GetByMessageTemplateIdAndUser(template.Id, userId, "WxApplet");
                    if (memberSubscribeMsg.SubscribeStatus == "accept")
                    {
                        UserOpenIds userOpenIds = new UserApp().GetUserOpenIdById(userId, "yuebon.openid.wxapplet");
                        if (userOpenIds != null)
                        {
                            WxJsonResult wxJsonResult = WxAppletSubscribeMessage.SendGoodNotice(userOpenIds.OpenId, template.WxAppletTemplateId, user.NickName, date, page);
                            result.ErrCode = wxJsonResult.errcode.ToString();
                            result.ErrMsg  = wxJsonResult.errmsg;
                        }
                    }
                }
                else
                {
                    result.Success = true;
                    result.ErrCode = "用户拒绝或未订阅";
                }
            }
            return(result);
        }
        public async Task<IActionResult> Register(UserPayment userPayment)
        {
            if (ModelState.IsValid)
            {
                UserApp userApp = new UserApp()
                {
                    Name= userPayment.UserName
                };

                _gameDbContext.UserApps.Add(userApp);
                _gameDbContext.SaveChanges();

                string IP = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

                int gameId = Convert.ToInt32(HttpContext.Session.GetString("gameId"));

                if (IP!=null)
                {
                    Payment payment = new Payment()
                    {
                        Amount = userPayment.Amount,
                        DateTime = userPayment.Date,
                        Status = true,
                        Ip = IP,
                        GameId=gameId
                    };

                    _gameDbContext.Payments.Add(payment);
                    _gameDbContext.SaveChanges();

                    return RedirectToAction("Index","Home");
                }
            }
            return View();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 获取当前用户
        /// </summary>
        /// <returns></returns>
        public async Task <CurrentUser> CurrentUser()
        {
            CurrentUser CurrentUser;

            if (!User.Identity.IsAuthenticated)
            {
                return(null);
            }
            if (bool.Parse(Configuration.GetSection("IsIdentity").Value))
            {
                //  var name = this.HttpContext.User.Claims.FirstOrDefault(o => o.Type == ClaimTypes.Name)?.Value;
                var name = HttpContext.User.Identity.Name;// User.Claims.FirstOrDefault(o => o.Type == ClaimTypes.Name)?.Value;
                var user = await UserApp.GetAsync(name);

                CurrentUser = new CurrentUser
                {
                    Avatar         = user.Avatar,
                    IsSys          = user.IsSys,
                    Id             = user.Id,
                    RoleId         = user.RoleId,
                    RealName       = user.RealName,
                    UserType       = "Saas",
                    AgentId        = 0,
                    LoginIPAddress = ""
                };
                return(CurrentUser);
            }
            string userdata = User.Claims.FirstOrDefault(o => o.Type == ClaimTypes.UserData).Value;

            return(CurrentUser.FromJson(userdata));
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> Edit(UserEditModel model)
        {
            if (!ModelState.IsValid)
            {
                return(Json(ResultDto.Err(GetErrorFromModelStateStr())));
            }

            if (!string.IsNullOrWhiteSpace(model.Avatar))
            {
                if (model.Avatar.Contains("["))
                {
                    var saveUrl = IMGOperate.BaseSave(ImagePathType.员工头像, model.Avatar);
                    model.Avatar = saveUrl;
                }
            }

            var m = await UserApp.GetAsync(model.Id);

            if (m == null)
            {
                return(Json(ResultDto.Err("数据不存在或已被删除")));
            }

            m = model.MapToMeg <UserEditModel, User>(m);

            var r = await UserApp.UpdateUserInfoAsync(m, await CurrentUser());

            return(Json(r));
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> ResetPasswordConfirm([Bind("Password")] ResetPasswordViewModel resetPasswordViewModel)
        {
            string  userId = TempData["UserId"].ToString();
            string  token  = TempData["Token"].ToString();
            UserApp user   = await UserManager.FindByIdAsync(userId);

            if (user != null)
            {
                IdentityResult result = await UserManager.ResetPasswordAsync(user, token, resetPasswordViewModel.Password);

                if (result.Succeeded)
                {
                    IdentityResult stampResult = await UserManager.UpdateSecurityStampAsync(user);

                    if (stampResult.Succeeded)
                    {
                        ViewBag.Status = "Successful";
                    }
                    else
                    {
                        AddModelError(result);
                    }
                }
                else
                {
                    AddModelError(result);
                }
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Linkin süresi dolmuştur. Yeni link alınız.");
            }
            return(View(resetPasswordViewModel));
        }
Ejemplo n.º 17
0
        public List <Mencion> recibirMenciones(UserApp usuario)
        {
            List <Mencion> aux = new List <Mencion>();

            aux = baseDatos.Query <Mencion>("select * from Mencion where idUsuario = " + usuario.idUsuario);
            return(aux);
        }
Ejemplo n.º 18
0
        private IActionResult BuildToken(UserApp user)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var expiration = DateTime.UtcNow.AddDays(1);

            var token = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Issuer"],
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration
            }));
        }
Ejemplo n.º 19
0
        public async Task <IActionResult> Register([FromForm] RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new UserApp
                {
                    Name     = model.Name,
                    UserName = model.Email,
                    Surname  = model.Surname,
                    Email    = model.Email,
                };

                var result = await UserManager.CreateAsync(user, model.Password);   //sprawdzenie hasła

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, false);   //zalogowanie od razu po rejestracji

                    return(RedirectToAction("login", "account"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            ViewBag.Error = true;
            return(View(model));
        }
Ejemplo n.º 20
0
 public ActionResult CheckLogin(string username, string password, string code)
 {
     try
     {
         User userEntity = new UserApp().CheckLogin(username, password);
         if (userEntity != null)
         {
             OperatorModel operatorModel = new OperatorModel();
             operatorModel.UserId             = userEntity.ID;
             operatorModel.UserCode           = userEntity.UserName;
             operatorModel.UserName           = userEntity.TrueName;
             operatorModel.CompanyId          = userEntity.OrgID;
             operatorModel.AccountType        = userEntity.AccountTypeID;
             operatorModel.RoleId             = userEntity.RoleID;
             operatorModel.LoginIPAddress     = Net.Ip;
             operatorModel.LoginIPAddressName = Net.GetLocation(operatorModel.LoginIPAddress);
             operatorModel.LoginTime          = DateTime.Now;
             operatorModel.LoginToken         = DESEncrypt.Encrypt(Guid.NewGuid().ToString());
             OperatorProvider.Provider.AddCurrent(operatorModel);
         }
         return(Content(new AjaxResult {
             state = ResultType.success.ToString(), message = "登录成功。"
         }.ToJson()));
     }
     catch (Exception ex)
     {
         return(Content(new AjaxResult {
             state = ResultType.error.ToString(), message = ex.Message
         }.ToJson()));
     }
 }
Ejemplo n.º 21
0
        protected void Application_Start()
        {
            UserAppService _userService = new UserAppService();
            RoleAppService _roleService = new RoleAppService();

            if (!_roleService.Any(x => x.Name == "Admin"))
            {
                RoleApp role1 = new RoleApp();
                role1.Name = "Admin";
                _roleService.Insert(role1);
            }
            if (!_roleService.Any(x => x.Name == "User"))
            {
                RoleApp role2 = new RoleApp();
                role2.Name = "User";
                _roleService.Insert(role2);
            }
            if (!_userService.Any(x => x.Email == "*****@*****.**"))
            {
                UserApp user = new UserApp();
                user.Email       = "*****@*****.**";
                user.Password    = CryptoService.MD5Password("123");
                user.UserName    = "******";
                user.CreateDate  = DateTime.Now;
                user.DateOfEntry = DateTime.Now;
                user.IsActive    = true;
                user.RoleId      = 1;
                _userService.Insert(user);
            }
            _userService.Dispose();
            _userService.Dispose();
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Creación de usuario estandar
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <UserAPI> CreateUser(UserAPI user)
        {
            if (!IsAdmin())
            {
                return(null);
            }

            var internalUser = new UserApp
            {
                UserName = user.Username,
                Name     = user.Name
            };

            var result = await _userManager.CreateAsync(internalUser, user.Password);

            if (result.Succeeded)
            {
                var userAdd = await _userManager.FindByNameAsync(user.Username);

                if (userAdd != null)
                {
                    await _userManager.AddToRoleAsync(userAdd, UserRol.RegularRol);
                }

                return(userAdd?.ToUserAPI());
            }

            return(null);
        }
Ejemplo n.º 23
0
        public IApplication ToUserApplication(MatchUsing MatchUsing)
        {
            var userApplication = new UserApp();

            userApplication.Name       = ApplicationName;
            userApplication.MatchUsing = MatchUsing;

            switch (MatchUsing)
            {
            case MatchUsing.WindowClass:
                userApplication.MatchString = WindowClass;
                break;

            case MatchUsing.WindowTitle:
                userApplication.MatchString = WindowTitle;
                break;

            case MatchUsing.ExecutableFilename:
                userApplication.MatchString = WindowFilename;
                break;
            }

            userApplication.IsRegEx = false;

            return(userApplication);
        }
Ejemplo n.º 24
0
        public async Task <bool> Register(Credentials credentials)
        {
            var user = new User()
            {
                Id    = Guid.NewGuid(),
                Email = credentials.Email,
            };

            user.Password = _passwordHasher.HashPassword(user, credentials.Password);
            try
            {
                await _context.AddAsync(user);

                await _context.SaveChangesAsync();
            }
            catch (System.Exception)
            {
                return(false);
            }

            var app = new UserApp()
            {
                UserId  = user.Id,
                AppId   = credentials.AppId,
                Default = true,
            };

            await _context.AddAsync(app);

            await _context.SaveChangesAsync();

            return(true);
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserApp user = new UserApp()
                {
                    Email = model.Email, UserName = model.Username, Country = model.Country
                };

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

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);

                    string baseUrl = $"{this.Request.Scheme}://{this.Request.Host}/";

                    return(Redirect(baseUrl));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Ejemplo n.º 26
0
        //Working
        public void AddUserApps(string blazerId, List <int> appIds, List <int> roleIds)
        {
            using (MyDbContext _db = new MyDbContext())
            {
                try
                {
                    var counter = 0;

                    while (counter <= appIds.Count - 1)
                    {
                        var newUserApp = new UserApp
                        {
                            BlazerId = blazerId,
                            AppId    = appIds[counter],
                            RoleId   = roleIds[counter]
                        };
                        _db.UserApps.Add(newUserApp);
                        _db.SaveChanges();
                        counter++;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }
            }
        }
Ejemplo n.º 27
0
        public static UserApp addApp( User user, String name, int appInfoId, String appTypeFullName, Boolean isDefault )
        {
            // 1) app

            //IApp app = Entity.New( appTypeFullName ) as IApp;
            IApp app = rft.GetInstance( "wojilu.Apps", appTypeFullName ) as IApp;

            app.OwnerId = user.Id;
            app.OwnerUrl = user.Url;
            app.OwnerType = typeof( User ).FullName;
            db.insert( app );

            // 2) userApp
            UserApp ua = new UserApp();
            ua.AppInfoId = appInfoId;
            ua.AppOid = app.Id;
            ua.Name = name;
            ua.Creator = user;
            ua.CreatorUrl = user.Url;
            ua.OwnerId = user.Id;
            ua.OwnerUrl = user.Url;
            ua.insert();

            // 3) menu
            // "wojilu.Apps.Blog.Domain.BlogApp";
            String appName = appTypeFullName.Split( '.' )[2];
            String path = string.Format( "{0}{1}/{0}/Index", appName, app.Id );
            addMenu( user, name, path, isDefault );

            return ua;
        }
Ejemplo n.º 28
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         if (HttpContext.Current.Session["userActive"] != null)
         {
             UserApp user        = new UserApp();
             UserApp userFromBdd = new UserApp();
             user = (UserApp)HttpContext.Current.Session["userActive"];
             IActiveUser activeUser = new UserActiveServiceImpl();
             userFromBdd = activeUser.getActiveUserById(user.usuario);
             if (userFromBdd != null && userFromBdd.usuario == user.usuario)
             {
                 //string flag = "ok";
                 //string txtUser = userFromBdd.nombres + " "+ userFromBdd.apellidos;
                 //((SiteMaster)this.Master).strName = txtUser;
                 Response.Redirect("~/BuscarProyectos.aspx", false);
             }
             else
             {
                 //string flag = "false";
                 Response.Redirect("~/UserPerfil.aspx", false);
             }
         }
     }
 }
Ejemplo n.º 29
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                UserApp user = new UserApp()
                {
                    Email = model.Email, UserName = model.Username, Country = model.Country
                };
                user.Token = TokenGenerator.Generate();
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);

                    AuthMessageSender sender  = new AuthMessageSender();
                    string            baseUrl = $"{this.Request.Scheme}://{this.Request.Host}/";
                    string            url     = baseUrl + "EmailConfirmed/" + user.Token;
                    string            message = EmailMessageGenerator.GenerateEmailConfirmMessage(url);

                    sender.SendEmailAsync(user.Email, "Please confirm your email", message);
                    return(Redirect(baseUrl));
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return(View(model));
        }
Ejemplo n.º 30
0
        public TokenDto CreateToken(UserApp userApp)
        {
            var accessTokenExpiration  = DateTime.Now.AddMinutes(_tokenOption.AccessTokenExpiration);
            var refreshTokenExpiration = DateTime.Now.AddMinutes(_tokenOption.RefreshTokenExpiration);
            var securityKey            = SignService.GetSymmetricSecurityKey(_tokenOption.SecurityKey);

            SigningCredentials signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: _tokenOption.Issuer,
                expires: accessTokenExpiration,
                notBefore: DateTime.Now,
                claims: GetClaims(userApp, _tokenOption.Audience),
                signingCredentials: signingCredentials
                );
            var handler = new JwtSecurityTokenHandler();

            var token = handler.WriteToken(jwtSecurityToken);

            var tokenDto = new TokenDto
            {
                AccessToken            = token,
                RefreshToken           = CreateRefreshToken(),
                AccessTokenExpiration  = accessTokenExpiration,
                RefreshTokenExpiration = refreshTokenExpiration
            };

            return(tokenDto);
        }
Ejemplo n.º 31
0
        private void FillUserApp()
        {
            string sqlString = "SELECT *,(SURNAME+' '+NAME) AS USERNAME FROM ACCOUNT WHERE UID=" + UC.UserId;

            sqlString             += " OR DIARYACCOUNT LIKE '|%" + UC.UserId.ToString() + "|%'";
            UserApp.DataTextField  = "UserName";
            UserApp.DataValueField = "uid";
            UserApp.DataSource     = DatabaseConnection.CreateDataset(sqlString);
            UserApp.DataBind();
            int actualUser;

            if (UC.ImpersonateUser == 0)
            {
                actualUser = UC.UserId;
            }
            else
            {
                actualUser = UC.ImpersonateUser;
            }
            UserApp.SelectedItem.Selected = false;
            foreach (ListItem li in UserApp.Items)
            {
                if (li.Value == actualUser.ToString())
                {
                    li.Selected = true;
                    break;
                }
            }
        }
Ejemplo n.º 32
0
 public AppEntry(UserApp app) {
     Path = app.Path;
     Name = app.Name;
     Args = app.Args;
     WorkingDir = app.WorkingDir;
     ShortcutKey = app.ShortcutKey;
 }
Ejemplo n.º 33
0
 private static ToolStripItem CreateMenuItem_AppLauncher(UserApp app, EventPack ep, ShellBrowserEx shellBrowser)
 {
     string path = app.Path;
     try {
         path = Environment.ExpandEnvironmentVariables(path);
     }
     catch {
     }
     MenuItemArguments mia = new MenuItemArguments(app, shellBrowser, MenuGenre.Application);
     if(path.StartsWith(@"\\") || path.StartsWith("::") || !Directory.Exists(path)) {
         mia.Target = MenuTarget.File;
         QMenuItem item = new QMenuItem(app.Name, mia) { Name = app.Name };
         item.SetImageReservationKey(path, Path.GetExtension(path));
         item.MouseMove += qmi_File_MouseMove;
         if(!ep.FromTaskBar && app.ShortcutKey != Keys.None) {
             item.ShortcutKeyDisplayString = QTUtility2.MakeKeyString(app.ShortcutKey).Replace(" ", string.Empty);
         }
         return item;
     }
     else {
         mia.Target = MenuTarget.Folder;
         DropDownMenuReorderable reorderable = new DropDownMenuReorderable(null) {
             MessageParent = ep.MessageParentHandle,
             ImageList = QTUtility.ImageListGlobal
         };
         reorderable.ItemRightClicked += ep.ItemRightClickEventHandler;
         DirectoryMenuItem item = new DirectoryMenuItem(app.Name) {
             Name = app.Name,
             Path = path,
             MenuItemArguments = mia,
             EventPack = ep,
             ModifiedDate = Directory.GetLastWriteTime(path),
             DropDown = reorderable,
             DoubleClickEnabled = true
         };
         item.DropDownItems.Add(new ToolStripMenuItem());
         item.DropDownItemClicked += realDirectory_DropDownItemClicked;
         item.DropDownOpening += realDirectory_DropDownOpening;
         item.DoubleClick += ep.DirDoubleClickEventHandler;
         item.SetImageReservationKey(path, null);
         return item;
     }
 }
Ejemplo n.º 34
0
 public MenuItemArguments(UserApp app, ShellBrowserEx shellBrowser, MenuGenre genre)
 {
     App = app;
     Path = app.Path;
     ShellBrowser = shellBrowser;
     Genre = genre;
 }