Ejemplo n.º 1
0
        public ClientTokenDto CreateTokenByClient(Client client)
        {
            var accessTokenExpiration = DateTime.Now.AddMinutes(_tokenOption.AccessTokenExpiration);

            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: GetClaimsByClient(client),
                signingCredentials: signingCredentials
                );
            var handler = new JwtSecurityTokenHandler();

            var token = handler.WriteToken(jwtSecurityToken);

            var tokenDto = new ClientTokenDto
            {
                AccessToken = token,

                AccessTokenExpiration = accessTokenExpiration,
            };

            return(tokenDto);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var service         = new SignService(new InMemoryUserRepo(), new EmailValidator(), new PasswordValidator());
            var loginController = new LoginController(service, new View());

            loginController.Run();
        }
Ejemplo n.º 3
0
 public static void UpdateAllSigns()
 {
     using (RockContext rockContext = new RockContext())
     {
         var signs = new SignService(rockContext)
                     .Queryable()
                     .Select(s => s);
         foreach (var sign in signs)
         {
             List <string> codes           = new List <string>();
             var           categoriesCodes = sign.SignCategories
                                             .Select(sc => sc.Codes)
                                             .ToList();
             foreach (var code in categoriesCodes)
             {
                 codes.AddRange(
                     (code ?? "")
                     .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                     .ToList()
                     );
             }
             MicroframeConnection signConnection = new MicroframeConnection(sign.IPAddress, sign.Port.AsIntegerOrNull() ?? 9107, sign.PIN);
             signConnection.UpdateMessages(codes);
         }
     }
 }
        public async Task SignOut([TimerTrigger("0 30 18 * * MON-FRI")] TimerInfo myTimer, ILogger log)
        {
            var authKey = _configuration["AuthToken"];
            var userId  = _configuration["UserId"];

            await SignService.Sign(authKey, Convert.ToInt32(userId));
        }
Ejemplo n.º 5
0
        public static void AddCustomTokenAuth(this IServiceCollection services, CustomTokenOption tokenOptions)
        {
            #region Authentication Mekanizm
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience[0],
                    IssuerSigningKey = SignService.GetSymetricSecurityKey(tokenOptions.SecurityKey),

                    //İmzasını dogruluyoruz.
                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,
                    //Token'a ömur verdiğimizde  default olarak 5 dk daha ekler
                    //5dk yı farklı zaman aralıklarındakı serverlara kurabılırsın
                    //bunu zero olarak verdiğimizde 5 dk lık sureyı 0'a 0 olarak tanımlıyoruz.
                    ClockSkew = TimeSpan.Zero
                };
            });
            #endregion
        }
Ejemplo n.º 6
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.º 7
0
        public ActionResult SignPreservationFilesToClose()
        {
            return(ActionResultHelper.TryCatchWithLogger(() =>
            {
                try
                {
                    CustomerCompanyViewModel customerCompany = Session["idCompany"] as CustomerCompanyViewModel;
                    List <Preservation> preservations = PreservationService.PreservationToClose(customerCompany.CompanyId);
                    Models.ArubaSignModel arubaSignModel = ArubaSignConfigurationHelper.GetArubaSignConfiguration(customerCompany.CompanyId, User.Identity.Name);
                    _logger.InfoFormat("Initializing signing with Aruba Automatic");
                    ISignService _signService = new SignService((info) => _logger.Info(info),
                                                                (err) => _logger.Error(err));

                    if (arubaSignModel == null)
                    {
                        return Json(ArubaSignConfigurationHelper.NO_CREDENTIALS, JsonRequestBehavior.AllowGet);
                    }
                    foreach (Preservation preservation in preservations)
                    {
                        SignDocuments(preservation, _signService, arubaSignModel);
                    }
                    return Json(ArubaSignConfigurationHelper.SIGN_COMPLETE, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {
                    _loggerService.Error($"Exception caught in process of signing: { ex.Message}", ex);
                    return Json(ArubaSignConfigurationHelper.SIGN_ERROR, JsonRequestBehavior.AllowGet);
                }
            }, _loggerService));
        }
Ejemplo n.º 8
0
        public void ConfigureServices(IServiceCollection services)
        {
            // DI Register
            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ITokenService, TokenService>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.AddScoped(typeof(IGenericService <,>), typeof(GenericService <,>));

            services.AddScoped <IUnitOfWork, UnitOfWork>();

            services.AddDbContext <AppDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SqlServer"), sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly("UdemyAuthServer.Data");
                });
            });

            services.AddIdentity <UserApp, IdentityRole>(Opt =>
            {
                Opt.User.RequireUniqueEmail         = true;
                Opt.Password.RequireNonAlphanumeric = false;
            }).AddEntityFrameworkStores <AppDbContext>().AddDefaultTokenProviders();

            services.Configure <CustumTokenOption>(Configuration.GetSection("TokenOption"));

            services.Configure <List <Client> >(Configuration.GetSection("Clients"));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
            {
                var tokenOptions = Configuration.GetSection("TokenOption").Get <CustumTokenOption>();
                opts.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience[0],
                    IssuerSigningKey = SignService.GetSymmetricSecurityKey(tokenOptions.SecurityKey),

                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "UdemyAuthServer.API", Version = "v1"
                });
            });
        }
Ejemplo n.º 9
0
        public IntegrationTest()
        {
            var configProvider = new TestConfigurationProvider();
            var mimeMapper     = new FileExtensionToMimeMapper();
            var httpClient     = new HttpClient();
            var apiClient      = new ApiClient(httpClient, configProvider, mimeMapper);
            var signService    = new SignService(configProvider);

            _gateway = new SecurionPayGateway(apiClient, configProvider, signService);
        }
Ejemplo n.º 10
0
        public void SignTest()
        {
            var mock = new Mock <ISecretKeyProvider>();

            mock.Setup(provider => provider.GetSecretKey()).Returns("pr_test_tXHm9qV9qV9bjIRHcQr9PLPa");
            var subject      = new SignService(mock.Object);
            var stringToSign = "{\"charge\":{\"amount\":499,\"currency\":\"EUR\"}}";
            var signature    = subject.Sign(stringToSign);

            Assert.AreEqual("cf9ce2d8331c531f8389a616a18f9578c134b784dab5cb7e4b5964e7790f173c", signature);
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddScoped <ITokenService, TokenService>();
            services.AddScoped(typeof(ICustomerService <,>), typeof(CustomerService <,>));
            services.AddScoped(typeof(IButtonService <>), typeof(ButtonService <>));
            services.AddScoped(typeof(ISliderService <>), typeof(SliderService <>));
            services.AddScoped(typeof(IDeviceService <,>), typeof(DeviceService <,>));
            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));
            services.AddScoped(typeof(IDeviceRepository), typeof(DeviceRepository));
            services.AddScoped(typeof(ICustomerRepository), typeof(CustomerRepository));
            services.AddScoped(typeof(IRepository <>), typeof(Repository <>));
            services.AddScoped(typeof(IService <, ,>), typeof(Service <, ,>));
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            services.AddDbContext <AppDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SqlServer"), sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly("KASSS.Data");
                });
            });
            services.AddIdentity <Customer, CustomerRole>(Opt =>
            {
                Opt.User.RequireUniqueEmail         = true;
                Opt.Password.RequireNonAlphanumeric = false;
            }).AddEntityFrameworkStores <AppDbContext>().AddDefaultTokenProviders();
            //define token option from appsettings
            services.Configure <CustomTokenOptions>(Configuration.GetSection("TokenOption"));
            services.Configure <List <Client> >(Configuration.GetSection("Clients"));

            //token check
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
            {
                var tokenOptions = Configuration.GetSection("TokenOption").Get <CustomTokenOptions>();
                opts.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer              = tokenOptions.Issuer,
                    ValidAudience            = tokenOptions.Audience[0],
                    IssuerSigningKey         = SignService.GetSymmetricSecurityKey(tokenOptions.SecurityKey),
                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });
        }
        // GET: SignDaily
        public ActionResult Index()
        {
            ViewBag.IsSign = false;
            SignService signService = new SignService();

            if (signService.IsSigned(UserName))
            {
                ViewBag.IsSign = true;
            }

            return(View());
        }
Ejemplo n.º 13
0
 private void SetConfig(ConfigAga oConfigAga, String path7Zdll)
 {
     try
     {
         this.configAga   = oConfigAga;
         this.signService = SignService.getInstance(this.configAga, path7Zdll);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message);
         Debug.WriteLine(ex.StackTrace);
     }
 }
Ejemplo n.º 14
0
        public async Task GetNextContestIdTest()
        {
            var context       = EssayCompetitionContextInMemoryFactory.InitializeContext();
            var futureContest = await this.seeder.SeedFutureContestAsync(context);

            var contestantContestRepository = new EfDeletableEntityRepository <ContestantContest>(context);
            var contestRepository           = new EfDeletableEntityRepository <Contest>(context);
            var service = new SignService(contestantContestRepository, contestRepository);

            var reusltedId = service.GetNextContestId();

            Assert.True(reusltedId == futureContest.Id, "GetNextContestId method does not work correctly");
        }
Ejemplo n.º 15
0
        public async Task UserAlreadyRegisteredForCompetitionTest()
        {
            var context           = EssayCompetitionContextInMemoryFactory.InitializeContext();
            var contestantContest = await this.seeder.SeedContestantContestAsync(context);

            var contestantContestRepository = new EfDeletableEntityRepository <ContestantContest>(context);
            var contestRepository           = new EfDeletableEntityRepository <Contest>(context);
            var service = new SignService(contestantContestRepository, contestRepository);

            var result = service.UserAlreadyRegisteredForCompetition(contestantContest.ContestantId, contestantContest.ContestId);

            Assert.True(result == true, "UserAlreadyRegisteredForCompetition method does not work correctly");
        }
Ejemplo 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.AddControllers();
            //Configuration ile appsettinjsona eriþebilirim

            services.AddScoped <IAuthenticationService, AuthenticationServices>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ITokenServices, CustomTokenService>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.AddScoped(typeof(IServiceGeneric <,>), typeof(ServicesGeneric <,>));
            services.AddScoped <IUnitOfWork, UnitOfWork>();

            services.AddDbContext <ProjeDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SqlServer"), sqlOptions =>
                {
                    sqlOptions.MigrationsAssembly("JWT.DATA");
                });
            });

            services.AddIdentity <Kullanici, IdentityRole>(Opt =>
            {
                Opt.User.RequireUniqueEmail         = true;
                Opt.Password.RequireNonAlphanumeric = false;
            }).AddEntityFrameworkStores <ProjeDbContext>().AddDefaultTokenProviders();

            services.Configure <CustomTokenOptions>(Configuration.GetSection("TokenAyar"));//CustomTokenOptionsu git appsettingjsondan al
            services.Configure <Client>(Configuration.GetSection("Clients"));


            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
            {
                var tokenOptionss = Configuration.GetSection("TokenAyar").Get <CustomTokenOptions>();
                opts.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer      = tokenOptionss.Issuer,
                    ValidAudience    = tokenOptionss.Audience[0],
                    IssuerSigningKey = SignService.SimetrikAnahtar(tokenOptionss.SecuritKey),

                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ClockSkew = TimeSpan.Zero
                };
            });
        }
Ejemplo n.º 17
0
        protected void gSigns_Delete(object sender, RowEventArgs e)
        {
            var         rockContext = new RockContext();
            SignService signService = new SignService(rockContext);
            Sign        sign        = signService.Get(e.RowKeyId);

            if (sign != null)
            {
                signService.Delete(sign);
                rockContext.SaveChanges();
            }

            BindGrid();
        }
Ejemplo n.º 18
0
        public async Task GetContestNameTest()
        {
            var context = EssayCompetitionContextInMemoryFactory.InitializeContext();

            await this.seeder.SeedContestAsync(context);

            var contestantContestRepository = new EfDeletableEntityRepository <ContestantContest>(context);
            var contestRepository           = new EfDeletableEntityRepository <Contest>(context);
            var service = new SignService(contestantContestRepository, contestRepository);

            var currentContext = context.Contests.First();
            var reusltedName   = service.GetContestName(currentContext.Id);

            Assert.True(currentContext.Name == reusltedName, "GetContestName method does not work correctly");
        }
        public ActionResult SignNow()
        {
            SignService signService = new SignService();

            if (signService.IsSigned(UserName))
            {
                return(Json(new ResultDTO {
                    Code = 0, Message = "已签到"
                }));
            }

            signService.DoSign(UserName);
            return(Json(new ResultDTO {
                Code = 1, Message = "签到成功"
            }));
        }
Ejemplo n.º 20
0
        public async Task RegisterForContestTest()
        {
            var context       = EssayCompetitionContextInMemoryFactory.InitializeContext();
            var futureContext = await this.seeder.SeedFutureContestAsync(context);

            var user = await this.seeder.SeedUserAsync(context, "*****@*****.**");

            var contestantContestRepository = new EfDeletableEntityRepository <ContestantContest>(context);
            var contestRepository           = new EfDeletableEntityRepository <Contest>(context);
            var service = new SignService(contestantContestRepository, contestRepository);

            await service.RegisterForContestAsync(user.Id, futureContext.Id);

            var contest = context.ContestantContest.FirstOrDefault();

            Assert.True(contest != null, "RegisterForContest method does not work correctly");
            Assert.True(contest.ContestantId == user.Id, "RegisterForContest method does not work correctly");
            Assert.True(contest.ContestId == futureContext.Id, "RegisterForContest method does not work correctly");
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var signService = new SignService(new RockContext());

            var signs = signService.Queryable()
                        .ToList()
                        .Select(s => new
            {
                Id         = s.Id,
                Name       = s.Name,
                IPAddress  = s.IPAddress,
                Port       = s.Port,
                Categories = string.Join(", ", s.SignCategories)
            })
                        .OrderBy(s => s.Name).ToList();

            gSigns.DataSource = signs;
            gSigns.DataBind();
        }
 public static void AddCustomTokenAuth(this IServiceCollection services, CustomTokenOption tokenOptions)
 {
     services.AddAuthentication(options =>
     {
         options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
         options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
     }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opt =>
     {
         opt.TokenValidationParameters = new TokenValidationParameters()
         {
             ValidIssuer              = tokenOptions.Issuer,
             ValidAudience            = tokenOptions.Audience[0],
             IssuerSigningKey         = SignService.GetSymmetricSecurityKey(tokenOptions.SecurityKey),
             ValidateIssuerSigningKey = true,
             ValidateAudience         = true,
             ValidateIssuer           = true,
             ValidateLifetime         = true,
             ClockSkew = TimeSpan.Zero
         };
     });
 }
Ejemplo n.º 23
0
        public JsonResult ValidateSignature(string content)
        {
            var message = "";

            //byte[] data = Convert.FromBase64String(content);
            //string xml = Encoding.UTF8.GetString(data);
            //var utils = _signService.GetXMLDigitalSignatureInfo(xml);

            SignService _signService = new SignService();
            bool        signInfo     = _signService.Verify(content);//, out exceptionsList);

            if (signInfo)
            {
                message = "Подписът е валиден!";
            }
            else
            {
                message = "Подписът НЕ е валиден!";
            }
            return(Json(new { message = message }));
        }
Ejemplo n.º 24
0
        public JsonResult GetSignatureInfo(string content)
        {
            TempData["XmlDocumentContent"] = content;
            SignService _signService = new SignService();
            var         signInfo     = _signService.GetXMLDigitalSignatureInfo(content);

            if (signInfo != null)
            {
                var resultObject = new
                {
                    issuarName       = signInfo.IssuerNameCommonName,
                    issuarAddress    = signInfo.IssuerAddress,
                    issuarIdentifier = signInfo.IssuerBulstat,

                    titularName         = signInfo.TitularName,
                    titularAddress      = signInfo.TitularAddres,
                    titularRegistration = signInfo.TitularOrgCourtRegistration,
                    authorQuality       = signInfo.AuthorQuality,

                    authorName    = signInfo.SubjectCommonName,
                    authorAddress = signInfo.SubjectAddress,


                    validFrom = signInfo.NotBefore.ToString("dd.MM.yyyy hh:mm:ss"),
                    validTo   = signInfo.NotAfter.ToString("dd.MM.yyyy hh:mm:ss"),

                    restriction  = signInfo.CretificateUsageRestrictions,
                    serialNumber = signInfo.SerialNumber
                };
                var result = new JavaScriptSerializer().Serialize(resultObject);
                return(Json(result));
            }
            else
            {
                return(Json(new { message = "Не са намерени данни за подпис" }));
            }
        }
Ejemplo n.º 25
0
        public static void AddCustomTokenAuth(this IServiceCollection services, CustomTokenOption tokenOptions)
        {
            // 2 ayrı üyelik sistemi olabilir -> bayiler için ayrı bir üyelik normal kullanıcılar için farklı login ekranları
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts => {
                opts.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience[0],
                    IssuerSigningKey = SignService.GetSymmetricSecurityKey(tokenOptions.SecurityKey),

                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,


                    ClockSkew = TimeSpan.Zero
                };
            });
        }
Ejemplo n.º 26
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Sign sign = null;

            var rockContext      = new RockContext();
            var signService      = new SignService(rockContext);
            var attributeService = new AttributeService(rockContext);

            int signId = int.Parse(hfSignId.Value);

            if (signId != 0)
            {
                sign = signService.Get(signId);
            }

            if (sign == null)
            {
                // Check for existing
                var existingDevice = signService.Queryable()
                                     .Where(k => k.Name == tbName.Text)
                                     .FirstOrDefault();
                if (existingDevice != null)
                {
                    nbDuplicateSign.Text    = string.Format("A sign already exists with the name '{0}'. Please use a different device name.", existingDevice.Name);
                    nbDuplicateSign.Visible = true;
                }
                else
                {
                    sign = new Sign();
                    signService.Add(sign);
                }
            }


            if (sign != null)
            {
                sign.Name        = tbName.Text;
                sign.PIN         = tbPIN.Text;
                sign.Description = tbDescription.Text;
                sign.IPAddress   = tbIPAddress.Text;
                sign.Port        = tbPort.Text;

                if (!sign.IsValid || !Page.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                var keys = SignCategories.Select(sc => sc.Key).ToList();
                foreach (var signCategory in sign.SignCategories.ToList())
                {
                    if (!keys.Contains(signCategory.Id))
                    {
                        sign.SignCategories.Remove(signCategory);
                    }
                }
                var newSignCategories = new SignCategoryService(rockContext).GetByIds(keys).ToList();
                foreach (var newSignCategory in newSignCategories)
                {
                    if (!sign.SignCategories.Select(sc => sc.Id).Contains(newSignCategory.Id))
                    {
                        sign.SignCategories.Add(newSignCategory);
                    }
                }


                rockContext.SaveChanges();

                NavigateToParentPage();
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="DeviceId">The device identifier.</param>
        public void ShowDetail(int signId)
        {
            pnlDetails.Visible = true;
            Sign sign = null;

            var rockContext = new RockContext();

            if (!signId.Equals(0))
            {
                sign = new SignService(rockContext).Get(signId);
                lActionTitle.Text = ActionTitle.Edit(Sign.FriendlyTypeName).FormatAsHtmlTitle();
                SignCategories    = new Dictionary <int, string>();
                foreach (var signCategory in sign.SignCategories)
                {
                    SignCategories.Add(signCategory.Id, signCategory.Name);
                }
            }

            if (sign == null)
            {
                sign = new Sign {
                    Id = 0
                };
                lActionTitle.Text = ActionTitle.Add(Sign.FriendlyTypeName).FormatAsHtmlTitle();
                sign.Port         = "9107";
            }

            hfSignId.Value = sign.Id.ToString();

            tbName.Text        = sign.Name;
            tbPIN.Text         = sign.PIN;
            tbDescription.Text = sign.Description;
            tbIPAddress.Text   = sign.IPAddress;

            if (sign.Port.IsNullOrWhiteSpace())
            {
                sign.Port = "9107";
            }
            tbPort.Text = sign.Port;

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Sign.FriendlyTypeName);
            }

            if (readOnly)
            {
                lActionTitle.Text = ActionTitle.View(Sign.FriendlyTypeName);
                btnCancel.Text    = "Close";
            }

            tbName.ReadOnly        = readOnly;
            tbPIN.ReadOnly         = readOnly;
            tbDescription.ReadOnly = readOnly;

            btnSave.Visible = !readOnly;

            BindSignCategories();
        }
Ejemplo n.º 28
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CustomTokenOption>(Configuration.GetSection("TokenOption"));

            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.AddScoped(typeof(IGenericService <,>), typeof(GenericService <,>));

            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddScoped <ICategoryService, CategoryService>();
            services.AddScoped <IArticleService, ArticleService>();
            services.AddScoped <ISavedArticleService, SavedArticleService>();
            services.AddScoped <ICommentService, CommentService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddScoped <ISecurityService, SecurityService>();
            services.AddScoped <ITokenService, TokenService>();
            services.AddTransient <IMailService, MailService>();
            services.AddScoped <IRoleService, RoleService>();

            services.AddScoped <ICommentRepository, CommentRepository>();
            services.AddScoped <ICategoryRepository, CategoryRepository>();
            services.AddScoped <IArticleRepository, ArticleRepository>();
            services.AddScoped <ISavedArticlesRepository, SavedArticleRepository>();
            services.AddScoped <IArticleLikeRepository, ArticleLikeRepository>();
            services.AddScoped <ISecurityCodeRepository, SecurityCodeRepository>();


            services.AddControllers().
            AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling =
                                  Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            services.AddDbContextPool <AppDbContext>(options =>
            {
                options.UseMySQL(Configuration["ConnectionStrings:HerokuPostgreSqlConnStr"], options =>
                {
                    options.MigrationsAssembly("BlogAppApi.Data");
                });
            });
            services.AddIdentity <AppUser, AppRole>(options =>
            {
                options.User.RequireUniqueEmail = true;

                //defaultta türkçe karakterler yok.
                options.User.AllowedUserNameCharacters =
                    "abcçdefgðhýijklmnoöpqrsþtuüvwxyzABCÇDEFGHIÝJKLMNOÖPQRSÞTUÜVWXYZ0123456789-._ ";

                options.Password.RequiredLength         = 4;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireDigit           = false;
                options.Lockout.AllowedForNewUsers      = false;
                options.SignIn.RequireConfirmedEmail    = false;
                options.Lockout.MaxFailedAccessAttempts = 5;
            }).AddEntityFrameworkStores <AppDbContext>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "My API", Version = "v1"
                });
            });


            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("http://localhost:4200",
                                        "https://localhost:5001").AllowAnyHeader()
                    .AllowAnyMethod();;
                });
            });

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
            {
                var tokenOptions = Configuration.GetSection("TokenOption").Get <CustomTokenOption>();
                opts.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience[0],
                    IssuerSigningKey = SignService.GetSymmetricSecurityKey(tokenOptions.SecurityKey),

                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,
                    ClockSkew = TimeSpan.Zero
                };
            });
        }
Ejemplo n.º 29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //  Scoped

            //  Tek bir istekte bir tane nesne örneği oluşacak aynı istekte birden fazla interface ile karşılaşırsa consturctor'da yine aynı nesne örneğini kullanıcak

            //  Transient

            //  Her interface ile karşılaştığında yeni bir nesne örneği

            //  Singleton

            //  Uygulama boyunca tek bir nesne örneği üzerinden çalışır.

            // DI Register

            services.AddScoped <IAuthenticationService, AuthenticationService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <ITokenService, TokenService>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.AddScoped(typeof(IServiceGeneric <,>), typeof(GenericService <,>));
            services.AddScoped <IUnitOfWork, UnitOfWork>();
            services.AddDbContext <AppDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SqlServer"), opt =>
                {
                    // migration işlemleri nerde gerçekleşicek ise o konumu belirtiyoruz.
                    opt.MigrationsAssembly("AuthServer.Data");
                });
            });

            services.AddIdentity <UserApp, IdentityRole>(opt =>
            {
                opt.User.RequireUniqueEmail         = true;
                opt.Password.RequireNonAlphanumeric = false;
            }).AddEntityFrameworkStores <AppDbContext>().AddDefaultTokenProviders(); // Şifre sıfırlamada default bir token oluşturmak için AddDefaultTokenProviders

            services.Configure <CustomTokenOption>(Configuration.GetSection("TokenOption"));
            services.Configure <List <Client> >(Configuration.GetSection("Clients"));

            // 2 ayrı üyelik sistemi olabilir -> bayiler için ayrı bir üyelik normal kullanıcılar için farklı login ekranları
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, opts =>
            {
                var tokenOptions = Configuration.GetSection("TokenOption").Get <CustomTokenOption>();
                opts.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidIssuer      = tokenOptions.Issuer,
                    ValidAudience    = tokenOptions.Audience[0],
                    IssuerSigningKey = SignService.GetSymmetricSecurityKey(tokenOptions.SecurityKey),

                    ValidateIssuerSigningKey = true,
                    ValidateAudience         = true,
                    ValidateIssuer           = true,
                    ValidateLifetime         = true,

                    ClockSkew = TimeSpan.Zero
                };
            });

            services.AddSwaggerGen(opt =>
            {
                opt.SwaggerDoc("doc", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title       = "AuthServer API",
                    Description = "AuthServer API Document",
                    Contact     = new Microsoft.OpenApi.Models.OpenApiContact
                    {
                        Email = "*****@*****.**",
                        Name  = "Samet Irkören",
                        Url   = new Uri("https://sametirkoren.com.tr")
                    }
                });
                opt.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
                {
                    In          = Microsoft.OpenApi.Models.ParameterLocation.Header,
                    Name        = "Authentication",
                    Type        = SecuritySchemeType.ApiKey,
                    Description = "Bearer {token}"
                });
            });

            services.AddControllers().AddFluentValidation(opt =>
            {
                opt.RegisterValidatorsFromAssemblyContaining <Startup>();
            }
                                                          );
            services.UseCustomValidationResponse();
        }
Ejemplo n.º 30
0
 public byte[] SoftSign(string CertificateName, string fname, byte[] blob)
 {
     return(SignService.Sign(blob, CertificateName));
 }