Skip to content

Commit

Permalink
API.NET project
Browse files Browse the repository at this point in the history
  • Loading branch information
Raymond Gao committed Jun 27, 2017
0 parents commit 3ccdba6
Show file tree
Hide file tree
Showing 85 changed files with 39,092 additions and 0 deletions.
Binary file added .DS_Store
Binary file not shown.
46 changes: 46 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceRoot}/bin/Debug/netcoreapp1.1/AdminAPI.dll",
"args": [],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"internalConsoleOptions": "openOnSessionStart",
"launchBrowser": {
"enabled": true,
"args": "${auto-detect-url}",
"windows": {
"command": "cmd.exe",
"args": "/C start ${auto-detect-url}"
},
"osx": {
"command": "open"
},
"linux": {
"command": "xdg-open"
}
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceRoot}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
16 changes: 16 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"version": "0.1.0",
"command": "dotnet",
"isShellCommand": true,
"args": [],
"tasks": [
{
"taskName": "build",
"args": [
"${workspaceRoot}/AdminAPI.csproj"
],
"isBuildCommand": true,
"problemMatcher": "$msCompile"
}
]
}
18 changes: 18 additions & 0 deletions AdminAPI.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="1.1.1" />
</ItemGroup>

</Project>
756 changes: 756 additions & 0 deletions Controllers/BCrypt.cs

Large diffs are not rendered by default.

57 changes: 57 additions & 0 deletions Controllers/PostsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using AdminAPI.Models;
using System.Linq;

namespace AdminAPI.Controllers
{
[Route("api/[controller]")]
public class PostsController : Controller
{
private readonly PostContext _context;

public PostsController(PostContext context)
{
_context = context;

if (_context.Posts.Count() == 0)
{
string timeStamp = DateTime.Now.ToString();
_context.Posts.Add(new Post { Content = string.Format("在 " + timeStamp + ": 创建新初始文本。") });
_context.SaveChanges();
}
}

[HttpGet]
public IEnumerable<Post> GetAll()
{
return _context.Posts.ToList();
}

[HttpGet("new", Name = "CreatePost")]
public IActionResult CreatePost(){
return View();
}

[HttpPost("new", Name = "AddPost")]
public IEnumerable<Post> AddPost(){
string content = Request.Form["content"];
string timeStamp = DateTime.Now.ToString();
_context.Posts.Add(new Post { Content = string.Format("在 " + timeStamp + ": " + content + "。") });
_context.SaveChanges();
return _context.Posts.ToList();
}

[HttpGet("{id}", Name = "GetPost")]
public IActionResult GetById(long id)
{
var item = _context.Posts.FirstOrDefault(t => t.Id == id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
}
}
15 changes: 15 additions & 0 deletions Controllers/PushController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Collections;
using Microsoft.AspNetCore.Mvc;
using AdminAPI.Models;
using System.Linq;
using System.Threading;

namespace AdminAPI.Controllers{
[Route("api/[controller]")]
public class PushController : Controller{
public PushController(){
}
}
}
28 changes: 28 additions & 0 deletions Controllers/SessionController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using AdminAPI.Models;
using System.Linq;

namespace AdminAPI.Controllers
{
[Route("[controller]")]
public class SessionController : Controller
{
private readonly UserContext _context;
private string generateSessionToken(){
string input = "abcdefghijklmnopqrstuvwxyz0123456789";
string[] result = new string[16];
Random random = new Random();
for(int i = 0; i < result.Length; i++){
result[i] = input[random.Next(0, input.Length)].ToString();
}
return string.Join("", result);
}
public SessionController(){

}


}
}
155 changes: 155 additions & 0 deletions Controllers/UserController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using AdminAPI.Models;
using System.Linq;
using System.Threading;

namespace AdminAPI.Controllers
{
[Route("[controller]")]
public class UserController : Controller
{
private readonly UserContext _context;
private string generateSessionToken(){
string input = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string[] result = new string[128];
Random random = new Random();
for(int i = 0; i < result.Length; i++){
result[i] = input[random.Next(0, input.Length)].ToString();
}
return string.Join("", result);
}

public UserController(UserContext context)
{
_context = context;
}
[HttpGet("show", Name="Show")]
public ActionResult Show(){
if(Request.Cookies["admin-api-session-token"] == null){
return RedirectToAction("Login", "Session");
}
var users = _context.Users.Where(u => u.SessionToken == Request.Cookies["admin-api-session-token"]);

if(users.Count() > 0){
ViewBag.Username = users.First().Username;

return View();
}else{
return RedirectToAction("Login", "User");
}
}

[HttpGet("new", Name="New")]
public IActionResult New(){
string pastSessionToken = Request.Cookies["admin-api-session-token"];
if(pastSessionToken != null){
var existingUser = _context.Users.Where(u => u.SessionToken == pastSessionToken);
if(existingUser.Count() > 0){
return RedirectToAction("Show", "User");
}
}
return View();
}
[HttpPost("create", Name="Create")]
public ActionResult Create(){
string userName = Request.Form["username"];
string passwordSalt = BCrypt.GenerateSalt();
string passwordDigest = BCrypt.HashPassword(Request.Form["password"], passwordSalt);
string createdAt = DateTime.Now.ToString();
string sessionToken = generateSessionToken();
_context.Users.Add(new User {
Username = userName,
PasswordDigest = passwordDigest,
PasswordSalt = passwordSalt,
CreatedAt = createdAt,
UpdatedAt = createdAt,
SessionToken = sessionToken
});
_context.SaveChanges();

Response.Cookies.Append("admin-api-session-token", sessionToken);
return RedirectToAction("Show", "User");
}

[HttpGet("login", Name="Login")]
public IActionResult Login(){
string pastSessionToken = Request.Cookies["admin-api-session-token"];
if(pastSessionToken != null){
var existingUser = _context.Users.Where(u => u.SessionToken == pastSessionToken);
if(existingUser.Count() > 0){
return RedirectToAction("Show", "User");
}
}
return View();
}

[HttpPost("create_session", Name="CreateSession")]
public IActionResult CreateSession(){
string username = Request.Form["username"];
string password = Request.Form["password"];

var user = _context.Users.Where(u => u.Username == username);
if(user.Count() < 1){
return RedirectToAction("New", "User");
}
string passwordDigest = user.First().PasswordDigest;

if(BCrypt.CheckPassword(password, passwordDigest)){
string sessionToken = generateSessionToken();
user.First().SessionToken = sessionToken;
Response.Cookies.Delete("admin-api-session-token");
Response.Cookies.Append("admin-api-session-token", sessionToken);
_context.SaveChanges();

return RedirectToAction("Show", "User");
}else{
return RedirectToAction("Login", "User");
}
}

[HttpPost("delete_session", Name="DeleteSession")]
public ActionResult DeleteSession(){
var sessionToken = generateSessionToken();
var user = _context.Users.Where(u => u.SessionToken == Request.Cookies["admin-api-session-token"]);
user.First().SessionToken = sessionToken;
_context.SaveChanges();
Response.Cookies.Delete("admin-api-session-token");

return RedirectToAction("Login", "User");
}

[HttpGet("panel", Name="ActionPanel")]
public IActionResult ActionPanel(){
return View();
}

[HttpGet("fetch/{id}", Name="Fetch")]
public List<string> Fetch(string id){
if(!Globals.pushStore.isSubscribed(id)){
Globals.pushStore.addSubscription(id);
}

while(!Globals.pushStore.shouldUpdate(id)){
Thread.Sleep(500);
}

return Globals.pushStore.newInfo(id);
}

[HttpPost("post/id={userId}&content={content}", Name="Post")]
public void Post(string userId, string content){
if(!Globals.pushStore.isSubscribed(userId)){
Globals.pushStore.addSubscription(userId);
}

Globals.pushStore.addInfo(userId, content);
}

[HttpDelete("delete/id={userId}", Name="Delete")]
public void Delete(string userId){
Globals.pushStore.removeSubscription(userId);
}
}
}
44 changes: 44 additions & 0 deletions Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace AdminAPI.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
Loading

0 comments on commit 3ccdba6

Please sign in to comment.