public KeyGenerationModule(ISContext serverContext) : base("/admin/keys", serverContext) { this.assertClaims(TokenAuthService.CLAIM_ADMIN); Post("/gen", _ => { var req = this.Bind <KeyGenerationRequest>(); if (req.amount < 1) { return(HttpStatusCode.BadRequest); } var newCodes = new List <string>(); for (var i = 0; i < req.amount; i++) { newCodes.Add(StringUtils.secureRandomString(16)); } serverContext.log.writeLine($"Admin generated {req.amount} invite keys", SLogger.LogLevel.Information); this.serverContext.appState.inviteKeys.AddRange(newCodes); return(Response.asJsonNet(newCodes)); }); Get("/active", _ => Response.asJsonNet(this.serverContext.appState.inviteKeys)); Delete("/delete/{key}", args => this.serverContext.appState.inviteKeys.Remove((string)args.key)); }
public AdministrationModule(ISContext serverContext) : base("/admin", serverContext) { this.assertClaims(TokenAuthService.CLAIM_ADMIN); Before += ctx => { userManager = new UserManagerService(serverContext); return(null); }; Get("/user/{id}", async args => { var user = await userManager.findUserByIdentifierAsync((string)args.id); return(Response.asJsonNet(user)); }); Put("/user/{id}", async args => { var user = await userManager.findUserByIdentifierAsync((string)args.id); var req = this.Bind <AdminUserModificationRequest>(); req.apply(user); await userManager.updateUserInDatabaseAsync(user); return(HttpStatusCode.NoContent); }); Get("/metrics/{id}", async args => { var user = await userManager.findUserByIdentifierAsync((string)args.id); var metrics = new UserMetricsService(serverContext, user.identifier).get(); return(Response.asJsonNet(metrics)); }); }
public UserModule(ISContext serverContext) : base("/user", serverContext) { this.assertClaims(TokenAuthService.CLAIM_USERNAME); Before += ctx => { userManager = new UserManagerService(serverContext); // update metrics new UserMetricsService(serverContext, ctx.CurrentUser.getClaim(TokenAuthService.CLAIM_IDENTIFIER)) .logEvent(MetricsEventType.UserApi); user = userManager .findUserByIdentifierAsync(ctx.CurrentUser.getClaim(TokenAuthService.CLAIM_IDENTIFIER)) .Result; return(null); }; Get("/", async _ => { return(Response.asJsonNet(user)); }); Put("/", async _ => { var req = this.Bind <UserModificationRequest>(); req.apply(user); await userManager.updateUserInDatabaseAsync(user); return(HttpStatusCode.NoContent); }); }
public MetaModule(ISContext serverContext) : base("/meta", serverContext) { Get("/", _ => { return(Response.asJsonNet(new { name = serverContext.configuration.name })); }); }
public ActionResult searchResults(string id) { ISContext db = new ISContext(); IEnumerable <Leadership> searchLeaderships = db.Leaderships.Where(s => s.Name.ToString().Contains(id)); ViewBag.searchLeaderships = searchLeaderships; IEnumerable <Man> searchMen = db.Men.Where(s => s.Name.ToString().Contains(id)); ViewBag.searchMen = searchMen; IEnumerable <Enterprise> searchEnterprises = db.Enterprises.Where(s => s.Title.ToString().Contains(id)); ViewBag.searchEnterprises = searchEnterprises; IEnumerable <Reward> searchRewards = db.Rewards.Where(s => s.Title.ToString().Contains(id)); ViewBag.searchRewards = searchRewards; return(View()); }
private static void PrintData() { // Gets and prints all books in database using (var context = new ISContext()) { var books = context.Book .Include(p => p.Publisher); foreach (var book in books) { var data = new StringBuilder(); data.AppendLine($"ISBN: {book.ISBN}"); data.AppendLine($"Title: {book.Title}"); data.AppendLine($"Publisher: {book.Publisher.Name}"); Console.WriteLine(data.ToString()); } } }
public HttpResponseMessage GetEnterprisePhoto(int id) { using (ISContext db = new ISContext()) { var enterprise = db.Enterprises.SingleOrDefault(e => e.Id == id); if (enterprise != null) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(enterprise.Photo) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); return(result); } return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }
public HttpResponseMessage GetLeadershipPhoto(int id) { using (ISContext db = new ISContext()) { var leadership = db.Leaderships.SingleOrDefault(l => l.Id == id); if (leadership != null) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(leadership.Photo) //Content = new ByteArrayContent(File.ReadAllBytes(@"D:\работа\anonsTV.jpg")) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); return(result); } return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }
private static void InsertData() { using (var context = new ISContext()) { // Creates the database if not exists context.Database.EnsureCreated(); // Adds a publisher var publisher = new Publisher { Name = "Mariner Books" }; context.Severs.Add(new Sever { SeverID = Guid.NewGuid(), CurrentCapaticy = 10 }); // Adds some books context.Book.Add(new Book { ISBN = "978-0544003415", Title = "The Lord of the Rings", Author = "J.R.R. Tolkien", Language = "English", Pages = 1216, Publisher = publisher }); context.Book.Add(new Book { ISBN = "978-0547247762", Title = "The Sealed Letter", Author = "Emma Donoghue", Language = "English", Pages = 416, Publisher = publisher }); // Saves changes context.SaveChanges(); } }
public HttpResponseMessage GetRewardPhoto(int id) { using (ISContext db = new ISContext()) { var reward = db.Rewards.SingleOrDefault(r => r.Id == id); if (reward != null) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(reward.Photo) //Content = new ByteArrayContent(File.ReadAllBytes(@"D:\работа\anonsTV.jpg")) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); return(result); } return(new HttpResponseMessage(HttpStatusCode.NotFound)); } // processing the stream. }
public DependencyObject(ISContext context) { serverContext = context; }
public MetadataModule(ISContext serverContext) : base("/meta", serverContext) { Get("/", _ => Response.asJsonNet(new { version = SContext.version })); }
public ActionResult Find(Request request) { try { dynamic res = null; dynamic obj = null; using (ISContext db = new ISContext()) { if (request.Obj == "Workers") { res = db.Database.SqlQuery <Worker>(request.RequestString).ToList(); obj = new Worker(); } if (request.Obj == "BookedTickets") { res = db.Database.SqlQuery <BookedTicket>(request.RequestString).ToList(); obj = new BookedTicket(); } if (request.Obj == "Buildings") { res = db.Database.SqlQuery <Building>(request.RequestString).ToList(); obj = new Building(); } if (request.Obj == "Equipments") { res = db.Database.SqlQuery <Equipment>(request.RequestString).ToList(); obj = new Equipment(); } if (request.Obj == "Events") { res = db.Database.SqlQuery <Event>(request.RequestString).ToList(); obj = new Event(); } if (request.Obj == "Orders") { res = db.Database.SqlQuery <Order>(request.RequestString).ToList(); obj = new Order(); } if (request.Obj == "Products") { res = db.Database.SqlQuery <Product>(request.RequestString).ToList(); obj = new Product(); } if (request.Obj == "Professions") { res = db.Database.SqlQuery <Profession>(request.RequestString).ToList(); obj = new Profession(); } if (request.Obj == "Rooms") { res = db.Database.SqlQuery <Room>(request.RequestString).ToList(); obj = new Room(); } if (request.Obj == "Tourists") { res = db.Database.SqlQuery <Tourist>(request.RequestString).ToList(); obj = new Tourist(); } if (request.Obj == "WorkPlaces") { res = db.Database.SqlQuery <WorkPlace>(request.RequestString).ToList(); obj = new WorkPlace(); } } Answer answer = new Answer { RequestString = request.RequestString, SearchResultObjects = res, Type = obj, JsonFile = JsonConvert.SerializeObject(res) }; return(View(answer)); } catch (Exception) { return(HttpNotFound()); } }
protected DependencyObject(ISContext context) { serverContext = context; }
public UserServiceTable(ISContext serverContext) : base(serverContext) { }
public static void map(IApplicationBuilder app, ISContext context) { app.Use(async(hc, n) => await acceptWebSocketClientsAsync(hc, n, context)); }
public UserManagerService(ISContext serverContext) : base(serverContext) { _userCollection = serverContext.database.GetCollection <UserIdentity>(REGISTERED_USERS_KEY); }
public UserMetricsService(ISContext context, string userIdentifier) : base(context) { _userIdentifier = userIdentifier; }
public WebSocketHandler(ISContext serverContext, WebSocket websocket) : base(serverContext) { _ws = websocket; _rtContext = new RealtimeContext(); }
public TokenAuthService(ISContext context) : base(context) { }
internal SBaseModule(string path, ISContext serverContext) : base($"/a{path}") { this.serverContext = serverContext; }
private void onUnload(ISContext sctx) { sctx.log.writeLine("Server unloading, force-persisting state data.", SLogger.LogLevel.Information); // persist on unload sctx.appState.persist(true); }
public AuthenticationModule(ISContext serverContext) : base("/auth", serverContext) { Before += ctx => { userManager = new UserManagerService(serverContext); tokenAuther = new TokenAuthService(serverContext); return(null); }; // Register account Post("/register", async args => { var charsetRegex = new Regex(@"^[a-zA-Z0-9._-]{3,24}$"); var req = this.Bind <UserRegistrationRequest>(); try { if (this.serverContext.configuration.maxUsers > -1 && userManager.userIdentityCount >= this.serverContext.configuration.maxUsers) { throw new SecurityException("Maximum number of users for this server reached"); } // Validate username charset if (charsetRegex.Matches(req.username).Count <= 0) { throw new InvalidParameterException("Invalid username."); } // Validate password if (req.password.Length < 8) { throw new InvalidParameterException("Password must be at least 8 characters."); } if (req.password.Length > 128) { throw new InvalidParameterException("Password may not exceed 128 characters."); } // Check invite key if enabled if (this.serverContext.configuration.inviteRequired) { // Validate invite key if (!this.serverContext.appState.inviteKeys.Remove(req.inviteKey)) { return(HttpStatusCode.PaymentRequired); } } // Attempt to register user var user = await userManager.registerUserAsync(req); // update metrics new UserMetricsService(serverContext, user.identifier) .logEvent(MetricsEventType.Auth); serverContext.log.writeLine($"Registered user {user.username} [{user.identifier}]", SLogger.LogLevel.Information); // queue persist this.serverContext.appState.queuePersist(); // Return user details return(bundleAuthorization(user)); } catch (NullReferenceException) { return(HttpStatusCode.BadRequest); } catch (SecurityException sx) { return(Response.AsText(sx.Message) .WithStatusCode(HttpStatusCode.Unauthorized)); } catch (InvalidParameterException sx) { return(Response.AsText(sx.Message) .WithStatusCode(HttpStatusCode.UnprocessableEntity)); } }); // Log in with username and password Post("/login", async args => { var req = this.Bind <UserLoginRequest>(); var user = await userManager.findUserByUsernameAsync(req.username); if (user == null) { return(HttpStatusCode.Unauthorized); } try { // Validate password if (user.enabled && await userManager.checkPasswordAsync(req.password, user)) { // update metrics new UserMetricsService(serverContext, user.identifier) .logEvent(MetricsEventType.Auth); // Return user details return(bundleAuthorization(user)); } return(HttpStatusCode.Unauthorized); } catch (NullReferenceException) { // A parameter was not provided return(HttpStatusCode.BadRequest); } catch (SecurityException ex) { // Registration blocked for security reasons return(Response.AsText(ex.Message) .WithStatusCode(HttpStatusCode.Unauthorized)); } }); Delete("/delete", async args => { // Login fields are the same as those for account deletion var req = this.Bind <UserLoginRequest>(); var user = await userManager.findUserByUsernameAsync(req.username); if (user == null) { return(HttpStatusCode.Unauthorized); } try { // Validate password if (user.enabled && await userManager.checkPasswordAsync(req.password, user)) { // Password was correct, delete account await userManager.deleteUserAsync(user.identifier); // queue persist this.serverContext.appState.queuePersist(); return(HttpStatusCode.NoContent); } return(HttpStatusCode.Unauthorized); } catch { return(HttpStatusCode.Unauthorized); } }); // Password change Patch("/pass", async args => { var req = this.Bind <UserPasswordChangeRequest>(); var user = await userManager.findUserByUsernameAsync(req.username); try { // Validate password if (req.newPassword.Length < 8) { throw new InvalidParameterException("Password must be at least 8 characters."); } if (req.newPassword.Length > 128) { throw new InvalidParameterException("Password may not exceed 128 characters."); } if (user.enabled && await userManager.checkPasswordAsync(req.oldPassword, user)) { // update metrics new UserMetricsService(serverContext, user.identifier) .logEvent(MetricsEventType.UpdateAuth); // Update password await userManager.changeUserPasswordAsync(user, req.newPassword); return(HttpStatusCode.NoContent); } return(HttpStatusCode.Unauthorized); } catch (NullReferenceException) { // A parameter was not provided return(new Response().WithStatusCode(HttpStatusCode.BadRequest)); } catch (SecurityException ex) { // Registration blocked for security reasons return(Response.AsText(ex.Message) .WithStatusCode(HttpStatusCode.Unauthorized)); } catch (InvalidParameterException ex) { return(Response.AsText(ex.Message) .WithStatusCode(HttpStatusCode.UnprocessableEntity)); } }); }
public static async Task acceptWebSocketClientsAsync(HttpContext hc, Func <Task> n, ISContext sctx) { if (!hc.WebSockets.IsWebSocketRequest) { return; } var ws = await hc.WebSockets.AcceptWebSocketAsync(); var h = new WebSocketHandler(sctx, ws); await h.eventLoopAsync(); }