Esempio n. 1
0
        public void ConnectionTest()
        {
            string expected = "Data Source=mssql.fhict.local;Initial Catalog=dbi414029;User ID=dbi414029;Password=***********";
            string actual   = AppSettingsJson.GetConnectionstring();

            Assert.AreEqual(expected, actual);
        }
Esempio n. 2
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var appSettingsJson  = AppSettingsJson.GetAppSettings();
            var connectionString = appSettingsJson["ConnectionStrings:DefaultConnection"];

            optionsBuilder.UseSqlServer(connectionString);
        }
Esempio n. 3
0
        public IActionResult Index()
        {
            var appSettingsJson  = AppSettingsJson.GetAppSettings();
            var connectionString = appSettingsJson["MssqlConnectionString"];

            return(View());
        }
Esempio n. 4
0
 public string SyncPatient()
 {
     try
     {
         Process p = new Process();
         //设置要启动的应用程序
         var appSettingsJson = AppSettingsJson.GetAppSettings();
         var processpath     = appSettingsJson["syncpatientapppath"];//admin12345
         p.StartInfo.FileName = processpath;
         //是否使用操作系统shell启动
         p.StartInfo.UseShellExecute = false;
         // 接受来自调用程序的输入信息
         p.StartInfo.RedirectStandardInput = true;
         //输出信息
         p.StartInfo.RedirectStandardOutput = true;
         // 输出错误
         p.StartInfo.RedirectStandardError = true;
         //不显示程序窗口
         p.StartInfo.CreateNoWindow = false;
         //启动程序
         p.Start();
         p.StandardInput.AutoFlush = true;
         //等待程序执行完退出进程
         p.WaitForExit();
         p.Close();
         return("同步成功");
     }
     catch (Exception)
     {
         return("同步失败");
     }
 }
Esempio n. 5
0
        public UserController()
        {
            Microsoft.Extensions.Configuration.IConfigurationRoot appSettingsJson = AppSettingsJson.GetAppSettings();
            string connectionString = appSettingsJson["DefaultConnection"];

            ConnectionString = connectionString;
        }
Esempio n. 6
0
        public IActionResult Index(string username, string pwd, bool logout = false)
        {
            //user admin12345
            if (logout || string.IsNullOrEmpty(username))
            {
                HttpContext.Session.SetString("user", "");
            }
            else
            {
                MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
                byte[]        data     = md5Hasher.ComputeHash(Encoding.Default.GetBytes(username + '-' + pwd));
                StringBuilder sBuilder = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }
                var appSettingsJson = AppSettingsJson.GetAppSettings();
                var userpwd         = appSettingsJson["userpwd"];//admin12345

                if (userpwd == sBuilder.ToString())
                {
                    HttpContext.Session.SetString("user", "admin");
                    ViewBag.Username = "******";
                }
                else
                {
                    ViewBag.ErrorMsg = "用户名密码错误";
                }
            }

            return(View());
        }
Esempio n. 7
0
        //连接数据库
        public SqlConnection Sqlconnect()
        {
            var           asp  = AppSettingsJson.GetAppSettings()["ConnectionStrings"];
            SqlConnection conn = new SqlConnection(asp);

            conn.Open();
            return(conn);
        }
Esempio n. 8
0
 public static void SaveAppSettings(AppSettingsJson settings)
 {
     IOUtils.EnsureParentDirExists(Paths.AppSettingsFile);
     File.WriteAllText(
         Paths.AppSettingsFile,
         JsonUtils.Serialize(settings)
         );
 }
Esempio n. 9
0
        public async Task <IActionResult> UploadFile(IFormFile FileToUpload, int fileGroupID)
        {
            if (FileToUpload == null || FileToUpload.Length == 0)
            {
                //return RedirectToAction("Manage", "LineItemGroups", new { id = fileGroupID });
                return(Json("\"error\" : \"No file uploaded\""));
            }
            string fileName = Path.GetFileName(FileToUpload.FileName);

            try {
                // 1. Save the FileAttachment record
                FileAttachment fileAttachment = new FileAttachment()
                {
                    FileDate    = DateTime.Now,
                    FileName    = fileName, //file name gets changed in next step below; done in two steps so we have the ID
                    DisplayName = fileName,
                    GroupID     = fileGroupID
                };
                _context.FileAttachments.Add(fileAttachment);
                _context.SaveChanges();

                // 2. Update the FileName to include the Attachment ID
                // This is to make the filename in the UserFiles directory unique
                // This will prevent overwrites by files with the same name
                // The DisplayName will remain identical to what the user uploaded, so it can duplicate without conflict
                fileAttachment.FileName = fileAttachment.AttachmentID + "_" + fileAttachment.FileName;
                _context.FileAttachments.Update(fileAttachment);
                _context.SaveChanges();

                // 3. Save the file to the UserFiles directory, using the FileName, not the DisplayName
                string filePath = AppSettingsJson.UserFilesPhysicalPath() + fileAttachment.FileName;
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await FileToUpload.CopyToAsync(stream);
                }
                // Assert: DisplayName = Filename.pdf, FileName = 123_Filename.pdf, file is stored in /UserFiles/123_Filename.pdf
                string displayPath = AppSettingsJson.UserFilesPhysicalPath() + fileAttachment.DisplayName;
                ViewData["FilePath"]    = filePath;
                ViewData["DisplayPath"] = displayPath;

                // Add to ViewBag a list of all files associated with this encumbrance request
                List <FileAttachment> files = _context.FileAttachments.Where(f => f.GroupID == fileGroupID).ToList();
                ViewBag.Files = files;
                //return RedirectToAction("Manage", "LineItemGroups", new { id = fileGroupID });
                string returnString = "{\"fileID\" : \"" + fileAttachment.AttachmentID + "\", \"fileName\" : \"" + fileAttachment.DisplayName + "\", \"fileURL\" : \"\\\\UserFiles\\\\" + fileAttachment.FileName + "\"}";
                return(Json(returnString));
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.Message);
                //TODO: If the file wasn't deleted, restore the FileAttachment record
                //return Json("{'error': 'true', 'message' : 'The attachment was not saved.' }");
                //return RedirectToAction("Manage", "LineItemGroups", new { id = fileGroupID });
                return(Json("\"error\" : \"Could not upload file.\""));
            }
        }
Esempio n. 10
0
 public void Delete(int id)
 {
     using (SqlConnection connection = new SqlConnection(AppSettingsJson.GetConnectionstring()))
     {
         connection.Open();
         string     query = @"Delete from [Users] where UserId = '" + id + "'";
         SqlCommand qry   = new SqlCommand(query, connection);
         qry.ExecuteNonQuery();
     }
 }
Esempio n. 11
0
 public void Add(UserModel user)
 {
     using (SqlConnection connection = new SqlConnection(AppSettingsJson.GetConnectionstring()))
     {
         connection.Open();
         string query = @"insert into [Users] (Name,Password,Age,Weight,Height, Gender) values ('" + user.Name + "','" + user.Password + "','" +
                        user.Age + "','" + user.Weight + "','" + user.Height + "','" + user.Gender + "')";
         SqlCommand qry = new SqlCommand(query, connection);
         qry.ExecuteNonQuery();
     }
 }
Esempio n. 12
0
        public DataAccess(string connectionStringName = "GoodBooks", string Database = "GoodBooks")
        {
            //Get connection string from appsettings
            var appSettingsJson = AppSettingsJson.GetAppSettings();

            connString = appSettingsJson["Data:ConnectionStrings:" + connectionStringName];

            //colnnect to cluster and select db
            _client = new MongoClient(connString);
            _db     = _client.GetDatabase(Database);
        }
Esempio n. 13
0
        public QueueSender()
        {
            var appSettings = AppSettingsJson.GetAppSettings();

            _settings = new QueueSettings(
                appSettings["SBusAzure:SBusConnectionString"],
                appSettings["SBusAzure:SBusQueueName"]);

            _queueClient = new QueueClient(
                _settings.ConnectionString, _settings.QueueName);
        }
Esempio n. 14
0
 public void UpdateUser(int id, string name, int age, int weight, int height, string gender)
 {
     using (SqlConnection conn = new SqlConnection(AppSettingsJson.GetConnectionstring()))
     {
         conn.Open();
         var query = @"update Users set Name ='" + name + "', Age ='" + age + "', Weight ='" + weight + "', Height ='" + height + "', Gender ='" + gender + "' where UserId = '" + id + "'";
         using (SqlCommand command = new SqlCommand(query, conn))
         {
             command.ExecuteNonQuery();
         }
     }
 }
        public async Task<UserLoginDTO> Register(UserRegisterDTO registerParam)
        {
            var Secret = AppSettingsJson.GetString("AppSettings:Secret");
            var key = Encoding.ASCII.GetBytes(Secret);

#if !DEBUG
            string encPassword = CyrptoHash.DecryptString(registerParam.Password, Convert.ToBase64String(key));
#else
            string encPassword = registerParam.Password;
#endif

            if (_userRepository.Get(x => x.Username == registerParam.Username) != null)
                throw new Exception($"Username is already exist! Username: {registerParam.Username}");

            try
            { MailAddress m = new MailAddress(registerParam.Email); }
            catch (FormatException)
            { throw new Exception($"Email format is incorrect! Email: {registerParam.Email}"); }

            var alreadyUser = await _userRepository.GetList(x => x.Email == registerParam.Email);
            if (alreadyUser.Any())
                throw new Exception($"Email is already exist! Email: {registerParam.Email}");

            var hasNumber = new Regex(@"[0-9]+");
            var hasUpperChar = new Regex(@"[A-Z]+");
            var hasMinimum8Chars = new Regex(@".{8,}");

            var isValidated = hasNumber.IsMatch(encPassword) && hasUpperChar.IsMatch(encPassword) && hasMinimum8Chars.IsMatch(encPassword);

            if (!isValidated)
                throw new Exception("The password must have at least one large character, one number and a length of more than 8 characters.");

            if (string.IsNullOrEmpty(registerParam.Picture))
                registerParam.Picture = "DefaultImg";

            encPassword = HashData.SHA512(encPassword);

            await _userRepository.Add(new User
            {
                Username = registerParam.Username,
                Biography = registerParam.Biography,
                CreateDate = DateTime.Now,
                Email = registerParam.Email,
                FullName = registerParam.FullName,
                LastSeen = DateTime.Now,
                Password = encPassword,
                Picture = registerParam.Picture,
                Status = Status.Active
            });

            return await Login(registerParam.Username, registerParam.Password);
        }
Esempio n. 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            #region Configurarion Injection v1

            var appConfig = new AppSettingsJson(); // 請先定義 AppSettings 類別
            Configuration.Bind(appConfig);


            services.AddSingleton <AppSettingsJson>(appConfig);

            #endregion

            #region Configurarion Injection v2

            services.Configure <AppSettingsJson>(Configuration);

            #endregion

            #region Configuration Injection v3
            services.Configure <AppSettingsSubJson>(
                Configuration.GetSection("Sub"));

            #endregion

            #region DI 練習

            services.AddTransient <IAppSettingsTransient, AppSettings>();

            services.AddScoped <IAppSettingsScoped, AppSettings>();

            services.AddSingleton <IAppSettingsSingleton, AppSettings>();

            #endregion

            #region 使用Session(建議不要用)

            services.AddDistributedMemoryCache();

            services.AddSession(options => { });

            #endregion


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Esempio n. 17
0
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            // To prep each database uncomment the corresponding line below.
            var appSettingsJson = AppSettingsJson.GetAppSettings();
            var con             = appSettingsJson["Finbuckle:MultiTenant:Stores:ConfigurationStore:Defaults:ConnectionString"];
            var tenantInfo      = new TenantInfo {
                ConnectionString = con
            };

            var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>();

            return(new ApplicationDbContext(tenantInfo, optionsBuilder.Options));
        }
Esempio n. 18
0
        public QueueReceiver(IProcess processData, ILogger <QueueReceiver <T> > logger)
        {
            var appSettings = AppSettingsJson.GetAppSettings();

            _settings = new QueueSettings(
                appSettings["SBusAzure:SBusConnectionString"],
                appSettings["SBusAzure:SBusQueueName"]);

            _processData = processData;
            _logger      = logger;
            _queueClient = new QueueClient(
                _settings.ConnectionString, _settings.QueueName);
        }
Esempio n. 19
0
        public ActionResult GetFileByName(string FileName, string DisplayName)
        {
            var fullName = AppSettingsJson.UserFilesPhysicalPath() + FileName;


            if (System.IO.File.Exists(fullName))
            {
                FileStream fs   = System.IO.File.OpenRead(fullName);
                byte[]     data = new byte[fs.Length];
                int        br   = fs.Read(data, 0, data.Length);
                if (br != fs.Length)
                {
                    throw new IOException("Unable to completely read file.");
                }

                //get MIME type; tried using methods in Microsoft.AspNetCore.StaticFiles; but can't install that package without a bunch of other conflicting dependencies
                string mimeType  = "application/octet-stream"; //default; not recommended to use this generic, but no other extensions have been used to date beyond what's listed in the switch below
                string extension = System.IO.Path.GetExtension(FileName);
                switch (extension)
                {
                case ".doc":
                    mimeType = "application/msword";
                    break;

                case ".docx":
                    mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                    break;

                case ".pdf":
                    mimeType = "application/pdf";
                    break;

                case ".xls":
                    mimeType = "application/vnd.ms-excel";
                    break;

                case ".xlsm":
                    mimeType = "application/vnd.ms-excel.sheet.macroEnabled.12";
                    break;

                case ".xlsx":
                    mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    break;
                }
                return(File(data, mimeType, DisplayName));
            }
            else
            {
                return(NotFound("File not found: " + FileName));
            }
        }
Esempio n. 20
0
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     try
     {
         var appSettingsJson   = AppSettingsJson.GetAppSettings();
         var connectionStrings = appSettingsJson["ConnectionStrings"];
         var connectionString  = appSettingsJson["EPSContext"];
         connectionString = "Data Source=USTLH1LT1506\\TurnpikeTest;Initial Catalog=EPSNew;Integrated Security=True";
     }
     catch (Exception e)
     {
         Console.Write(e.StackTrace.ToString());
     }
 }
Esempio n. 21
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            #region JWT

            var key = Encoding.ASCII.GetBytes(AppSettingsJson.GetString("AppSettings:Secret"));

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            #endregion

            #region INJECTION

            services.AddTransient <IUserService, UserManager>();
            services.AddTransient <IUserRepository, EFUserRepository>();

            services.AddScoped <IPostRepository, EFPostRepository>();
            services.AddScoped <IPostService, PostManager>();

            services.AddScoped <IFollowerRepository, EFFollowerRepository>();
            services.AddScoped <IFollowerService, FollowerManager>();

            services.AddScoped <IPhotoRepository, EFPhotoRepository>();
            services.AddScoped <IPhotoService, PhotoManager>();


            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            #endregion
        }
        public PackStartupWindowViewModel(
            IAttachedWindowManipulator attachedWindowManipulator,
            AppSettingsJson appSettings
            )
        {
            _attachedWindowManipulator = attachedWindowManipulator;
            _appSettings = appSettings;

            CreateNewPackCommand      = new ActionCommand(CreateNewPackCommand_Execute);
            ChooseExistingPackCommand = new ActionCommand(ChooseExistingPackCommand_Execute);
            LaunchConverterCommand    = new ActionCommand(LaunchConverterCommand_Execute);
            SwitchToEnglishCommand    = new ActionCommand(() => SwitchLanguageTo("en-US"));
            SwitchToRussianCommand    = new ActionCommand(() => SwitchLanguageTo("ru-RU"));

            PropertyChanged += OnPropertyChanged;
        }
Esempio n. 23
0
        public JobContainer(IJobExecutionContext _Context)
        {
            var config = AppSettingsJson.GetAppSettings();

            SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(config.GetSection("ConnectionStrings:BaseDBContext").Value);

            sqlConnectionStringBuilder.Password = Encryption.Decrypt(sqlConnectionStringBuilder.Password);
            ConnString = sqlConnectionStringBuilder.ConnectionString;

            stopwatch.Start();
            Context = _Context;

            JobName = JobGroup = MethodName = MethodParams = JobMessage = ExceptionInfo = "";
            JobName = Context.JobDetail.Key.Name;
            InitContainer();
        }
Esempio n. 24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var appSettingsJson = AppSettingsJson.GetAppSettings();

            services.AddDbContext <DataContext>(opts => opts.UseSqlServer(appSettingsJson["ConnectionString:ReceiptsDBAzure"]));
            services.AddScoped <IDataRepository <Receipt>, ReceiptManager>();
            services.AddScoped <IDataRepository <User>, UserManager>();

            services.BuildServiceProvider().GetService <DataContext>().Database.Migrate();
            services.AddOpenApiDocument(config => config.Title = "API");
            services.AddControllers();

            services.AddApiVersioning(config =>
            {
                config.DefaultApiVersion = new ApiVersion(1, 0);
                config.AssumeDefaultVersionWhenUnspecified = true;
                config.ReportApiVersions = true;
            });
        }
Esempio n. 25
0
        public JsonResult Delete(int id)
        {
            try
            {
                //Delete the FileAttachment Record
                FileAttachment fileAttachment = _context.FileAttachments.SingleOrDefault(f => f.AttachmentID == id);
                string         fileName       = fileAttachment.DisplayName;
                _context.FileAttachments.Remove(fileAttachment);
                _context.SaveChanges();

                //Remove the file from UserFiles directory
                DeleteFile(AppSettingsJson.UserFilesPhysicalPath() + fileAttachment.FileName);

                return(new JsonResult("{\"fileName\" : \"" + fileName + "\"}"));
            }catch (Exception e)
            {
                return(new JsonResult("result: error"));
            }
        }
Esempio n. 26
0
        public static async Task Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            // Set up the databases for the sample if needed.
            var env = host.Services.GetService <IWebHostEnvironment>();

            if (env.EnvironmentName == "Development")
            {
                var appSettingsJson = AppSettingsJson.GetAppSettings();
                var con             = appSettingsJson["Finbuckle:MultiTenant:Stores:ConfigurationStore:Defaults:ConnectionString"];
                using (var db = new ApplicationDbContext(new TenantInfo {
                    ConnectionString = con
                }))
                {
                    await db.Database.MigrateAsync();
                }
            }

            await host.RunAsync();
        }
Esempio n. 27
0
        public IActionResult PatientDetails()
        {
            List <string> OutPut = new List <string>();
            //Dictionary<string, string> dict = new Dictionary<string, string>();

            // string connectionString = "Server = demosql001.cc4mi4fhf4fo.ap-southeast-2.rds.amazonaws.com; Database = WHADemo; User Id = whadevfe; Password = 4MeW3%T7JxMA; ";
            //string connectionString = "SELECT TOP (1000) [PersonID],[LastName],[FirstName],[Address],[City] FROM [testdatabase].[dbo].[Persons]";
            //string connectionString = "Data Source=DESKTOP-SK0EJ1N;Initial Catalog=testdatabase;Integrated Security=True";
            //var xxx = ConfigurationManager.ConnectionStrings["DefaultConnectString"];
            //string myDb1ConnectionString = _configuration.GetConnectionString("myDb1");
            var appSettingsJson  = AppSettingsJson.GetAppSettings();
            var connectionString = appSettingsJson["DefaultConnectString"];
            //string connectionString = "dfa";
            SqlConnection conn = new SqlConnection(connectionString);

            conn.Open();
            //SqlCommand com = new SqlCommand("select * from dbo.POBPatient where POBPatientID = 1;", conn);
            SqlCommand com      = new SqlCommand("select * from dbo.Persons;", conn);
            var        Returned = com.ExecuteReader();

            while (Returned.Read())
            {
                for (int i = 0; i < Returned.FieldCount; i++)
                {
                    OutPut.Add(Returned.GetName(i));

                    // columns.Add(Returned.GetName(i));
                }

                //OutPut.Add(Returned.GetString(3));
            }
            conn.Close();

            var column = new PatientEmpolymentHistory();

            //column.ColumnNames = OutPut;

            return(Ok(OutPut));
        }
Esempio n. 28
0
        public ApiRequest(string System, bool LoginFlag = false)
        {
            Stopwatch = new Stopwatch();
            Stopwatch.Start();

            _System    = System;
            _LoginFlag = LoginFlag;
            try
            {
                var config = AppSettingsJson.GetAppSettings();
                ConnString = config.GetSection("ConnectionStrings:BaseDBContext").Value;

                SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder(ConnString);
                sqlConnectionStringBuilder.Password = Encryption.Decrypt(sqlConnectionStringBuilder.Password);
                ConnString = sqlConnectionStringBuilder.ConnectionString;

                Server   = config.GetSection(System + "Setting:Server").Value;
                LoginUrl = config.GetSection(System + "Setting:LoginUrl").Value;
                Uid      = config.GetSection(System + "Setting:Uid").Value;
                Pwd      = config.GetSection(System + "Setting:Pwd").Value;
            }
            catch (Exception) { }
        }
Esempio n. 29
0
 public UserModel FindById(int id)
 {
     using (SqlConnection connection = new SqlConnection(AppSettingsJson.GetConnectionstring()))
     {
         try
         {
             connection.Open();
             SqlCommand dataCommand = new SqlCommand()
             {
                 CommandText = "SELECT * FROM [dbo].[Users] WHERE [UserId] = '" + id + "'",
                 Connection  = connection
             };
             using (SqlDataReader userReader = dataCommand.ExecuteReader())
             {
                 userReader.Read();
                 return(new UserModel(Convert.ToInt32(userReader["UserId"]), userReader["Password"].ToString(), userReader["Name"].ToString(), Convert.ToInt32(userReader["Age"]), Convert.ToInt32(userReader["Weight"]), Convert.ToInt32(userReader["Height"]), userReader["Gender"].ToString()));
             }
         }
         catch
         {
             return(null);
         }
     }
 }
        public async Task<UserLoginDTO> Login(string username, string password)
        {
            var key = Encoding.ASCII.GetBytes(AppSettingsJson.GetString("AppSettings:Secret"));

            password = CyrptoHash.DecryptString(password, Convert.ToBase64String(key));
            //Sql de şifreli tutuluor.
            password = HashData.SHA512(password);

            var user = await _userRepository.Get(x => x.Username == username && x.Password == password && x.Status == Status.Active);

            if (user == null) return null;

            var tokenHandler = new JwtSecurityTokenHandler();

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString()),
                    new Claim(ClaimTypes.Role,user.ProfileType.ToString())
                }),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var tokenSecret = tokenHandler.CreateToken(tokenDescriptor);
            string token = tokenHandler.WriteToken(tokenSecret);

            return new UserLoginDTO
            {
                FullName = user.FullName,
                Id = user.Id,
                Password = null,
                Username = user.Username,
                Token = token
            };
        }