public async Task <object> UpdateAsync( [FromBody] WriteNewsItemRequest body) { var newsItem = await _newsItemRepository.GetAsync(body.Id); if (newsItem == null) { return(NotFound(JResponse.Error("News item not found."))); } newsItem.Modified = DateTime.UtcNow; if (body.Title != null) { newsItem.Title = body.Title; } if (body.Html != null) { newsItem.Html = body.Html; } if (body.Published == true) { newsItem.Published = DateTime.UtcNow; } _logger.LogInformation($"Updating news item: {newsItem.Title} (updated by {User.Identity.Name}"); await _newsItemRepository.UpdateAsync(newsItem); return(JResponse.OK()); }
public async Task <object> GetServersAsync( [FromServices] HttpClient httpClient, [FromServices] IServerRepository serverRepository) { var accept = HttpContext.Request.Headers[HeaderNames.Accept]; var accepts = accept .SelectMany(x => x.Split(',', StringSplitOptions.RemoveEmptyEntries)) .ToArray(); var returnJson = accepts.Contains(MimeTypes.ApplicationJson, StringComparer.InvariantCultureIgnoreCase) || accepts.Contains(MimeTypes.TextJson, StringComparer.InvariantCultureIgnoreCase); try { // A good time to clean up any expired servers await DoServerCleanupAsync(serverRepository); #if DEBUG var servers = await GetServersFromLiveSiteAsync(httpClient); #else var servers = await serverRepository.GetAllAsync(); #endif if (returnJson) { var response = new JGetServersResponse() { status = JStatus.OK, Servers = servers }; return(ConvertResponse(response)); } else { servers = servers .OrderByDescending(x => x.Players) .ThenBy(x => x.RequiresPassword) .ThenByNaturalDescending(x => x.Version) .ThenBy(x => x.Name) .ToArray(); return(View("Views/Servers.cshtml", servers)); } } catch { var msg = "Unable to connect to fetch servers."; if (returnJson) { return(ConvertResponse(JResponse.Error(msg))); } else { return(StatusCode(StatusCodes.Status500InternalServerError, msg)); } } }
protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context) { HttpResponse httpResponse = Context.Response; httpResponse.Headers[HeaderNames.ContentType] = MimeTypes.ApplicationJson; string response = JsonConvert.SerializeObject(JResponse.Error(JErrorMessages.InvalidToken)); await httpResponse.WriteAsync(response); return(false); }
public async Task <object> VerifyAsync( [FromServices] UserAccountService userAccountService, [FromQuery] string token) { if (await userAccountService.VerifyAccountAsync(token)) { return(JResponse.OK()); } else { return(BadRequest(JResponse.Error("Invalid token"))); } }
public async Task <object> DeleteAsync( [FromBody] WriteNewsItemRequest body) { if (body.Id == null) { return(BadRequest(JResponse.Error("News item id not specified."))); } _logger.LogInformation($"Deleting news item: {body.Id} (deleted by {User.Identity.Name}"); await _newsItemRepository.DeleteAsync(body.Id); return(JResponse.OK()); }
public async Task <IJResponse> Login( [FromServices] OpenRCT2org.IUserApi userApi, [FromServices] IUserSessionRepository userSessionRepository, [FromServices] DB.Abstractions.IUserRepository userRepository, [FromBody] JLoginRequest body) { try { Guard.ArgumentNotNull(body); Guard.ArgumentNotNull(body.user); Guard.ArgumentNotNull(body.password); } catch { return(JResponse.Error(JErrorMessages.InvalidRequest)); } _logger.LogInformation("User login: {0}", body.user); OpenRCT2org.JUser orgUser; try { orgUser = await userApi.AuthenticateUser(body.user, body.password); } catch (OpenRCT2org.OpenRCT2orgException) { return(JResponse.Error(ErrorAuthenticationFailed)); } var ourUser = await userRepository.GetUserFromOpenRCT2orgIdAsync(orgUser.userId); if (ourUser == null) { ourUser = new DB.Models.User() { OpenRCT2orgId = orgUser.userId, UserName = orgUser.name }; await userRepository.InsertUserAsync(ourUser); } string token = await userSessionRepository.CreateToken(orgUser.userId); return(new JLoginResponse() { status = JStatus.OK, user = orgUser.name, token = token }); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.Controller is Controller controller) { var modelState = controller.ModelState; if (modelState?.IsValid == false) { var firstError = new SerializableError(modelState).FirstOrDefault(); var message = "Invalid request"; if (firstError.Value is string[] messages && messages.Length != 0) { message = messages[0]; } filterContext.Result = controller.BadRequest(JResponse.Error(message)); } } base.OnActionExecuting(filterContext); }
public async Task <IJResponse> AdvertiseHeartbeat( [FromServices] IServerRepository serverRepository, [FromBody] JAdvertiseHeartbeatRequest body) { Server server = await serverRepository.GetByToken(body.token); if (server == null) { return(JResponse.Error("Server not registered.")); } server.Players = body.players; server.GameInfo = body.gameInfo; server.LastHeartbeat = DateTime.Now; await serverRepository.AddOrUpdate(server); return(ConvertResponse(JResponse.OK())); }
public async Task <object> SignInAsync( [FromServices] UserAuthenticationService userAuthenticationService, [FromBody] SignInRequest body) { var(user, authToken) = await userAuthenticationService.AuthenticateAsync(body.Username, body.Password); if (authToken == null) { var result = JResponse.Error("Invalid username or password."); return(StatusCode(StatusCodes.Status401Unauthorized, result)); } return(new { status = JStatus.OK, token = authToken.Token, user = GetProfileInfo(user) }); }
public async Task <object> PutAsync( [FromRoute] string name, [FromBody] UpdateUserRequest body) { var user = await _userRepository.GetUserFromNameAsync(name.ToLower()); if (user == null) { return(NotFound(JResponse.Error("User not found"))); } _logger.LogInformation($"Updating user: {user.Name}"); if (body.Bio != null) { user.Bio = body.Bio; } await _userRepository.UpdateUserAsync(user); return(JResponse.OK()); }
public async Task <object> GetAsync(string name) { var user = await _userRepository.GetUserFromNameAsync(name.ToLower()); if (user == null) { return(NotFound(JResponse.Error("User not found"))); } return(new { Status = JStatus.OK, Result = new { user.Name, user.Bio, Joined = user.Created.ToString("d MMMM yyyy"), Comments = 0, Uploads = 0, Traits = new [] { "Developer", "Streamer" }, Avatar = GetAvatarUrl(user) } }); }
public async Task <object> CreateAsync( [FromServices] GoogleRecaptchaService recaptchaService, [FromServices] UserAccountService userAccountService, [FromBody] CreateUserRequest body) { var remoteIp = HttpContext.Connection.RemoteIpAddress.ToString(); if (!await recaptchaService.ValidateAsync(remoteIp, body.Captcha).ConfigureAwait(false)) { return(BadRequest(JResponse.Error("reCAPTCHA validation failed."))); } if (!await userAccountService.IsNameAvailabilityAsync(body.Username)) { return(BadRequest(JResponse.Error("User name already taken."))); } if (!await userAccountService.IsEmailAvailabilityAsync(body.Email)) { return(BadRequest(JResponse.Error("Email address already registered."))); } await userAccountService.CreateAccountAsync(body.Username, body.Email, body.Password); return(JResponse.OK()); }
public async Task <IJResponse> AdvertiseHeartbeatAsync( [FromServices] IServerRepository serverRepository, [FromBody] JAdvertiseHeartbeatRequest body) { if (string.IsNullOrEmpty(body?.Token)) { return(ConvertResponse(JResponse.Error(JErrorMessages.InvalidToken))); } Server server = await serverRepository.GetByTokenAsync(body.Token); if (server == null) { return(ConvertResponse(JResponse.Error(JErrorMessages.ServerNotRegistered))); } server.Players = body.Players; server.GameInfo = body.GameInfo; server.LastHeartbeat = DateTime.Now; await serverRepository.AddOrUpdateAsync(server); return(ConvertResponse(JResponse.OK())); }
public async Task <IJResponse> Logout( [FromServices] IUserSessionRepository userSessionRepository, [FromBody] JLogoutRequest body) { try { Guard.ArgumentNotNull(body); Guard.ArgumentNotNull(body.token); } catch { return(JResponse.Error(JErrorMessages.InvalidRequest)); } if (await userSessionRepository.RevokeToken(body.token)) { return(JResponse.OK()); } else { return(JResponse.Error(JErrorMessages.InvalidToken)); } }
public async Task <object> GetServers( [FromServices] IServerRepository serverRepository) { try { Server[] servers = await serverRepository.GetAll(); JServer[] jServers = servers.Select(x => JServer.FromServer(x)) .ToArray(); await DoServerCleanup(serverRepository); var response = new JGetServersResponse() { status = JStatus.OK, servers = jServers }; return(ConvertResponse(response)); } catch { return(ConvertResponse(JResponse.Error("Unable to connect to fetch servers."))); } }
public async Task <IJResponse> AdvertiseServerAsync( [FromServices] IServerRepository serverRepository, [FromServices] Random random, [FromBody] JAdvertiseServerRequest body) { var remoteAddress = GetRemoteAddress(); if (String.IsNullOrEmpty(remoteAddress)) { return(JResponse.Error(JErrorMessages.ServerError)); } Server serverInfo; try { string serverInfoJson; using (var client = new OpenRCT2Client()) { _logger.LogInformation("Connecting to {0}:{1}", remoteAddress, body.Port); await client.Connect(remoteAddress, body.Port); _logger.LogInformation("Requesting server info from {0}:{1}", remoteAddress, body.Port); serverInfoJson = await client.RequestServerInfo(); } serverInfo = JsonConvert.DeserializeObject <Server>(serverInfoJson); } catch (SocketException) { return(ConvertResponse(JResponse.Error("Unable to connect to server, make sure your ports are open."))); } catch (TimeoutException) { return(ConvertResponse(JResponse.Error("Timed out while waiting for server response."))); } catch { return(ConvertResponse(JResponse.Error("Unable to advertise server."))); } var token = random.NextBytes(8) .ToHexString(); var server = new Server() { Token = token, LastHeartbeat = DateTime.Now, Addresses = new ServerAddressList() { IPv4 = new string[] { remoteAddress }, IPv6 = new string[0] }, Port = body.Port, Name = serverInfo.Name, Description = serverInfo.Description, Provider = serverInfo.Provider, RequiresPassword = serverInfo.RequiresPassword, Players = serverInfo.Players, MaxPlayers = serverInfo.MaxPlayers, Version = serverInfo.Version }; _logger.LogInformation("Registering server {0} [{1}:{2}]", serverInfo.Name, remoteAddress, body.Port); await serverRepository.AddOrUpdateAsync(server); var response = new JAdvertiseServerResponse() { status = JStatus.OK, Token = token }; return(ConvertResponse(response)); }