|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using Microsoft.AspNetCore.Mvc; |
| 5 | +using Microsoft.Azure.WebJobs; |
| 6 | +using Microsoft.Azure.WebJobs.Extensions.Http; |
| 7 | +using Microsoft.AspNetCore.Http; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Newtonsoft.Json; |
| 10 | +using Newtonsoft.Json.Linq; |
| 11 | +using System.Collections.Generic; |
| 12 | +using System.Linq; |
| 13 | +using System.Data; |
| 14 | +using Microsoft.Data.SqlClient; |
| 15 | +using Microsoft.EntityFrameworkCore; |
| 16 | +using Microsoft.EntityFrameworkCore.Design; |
| 17 | +using System.ComponentModel.DataAnnotations.Schema; |
| 18 | +using System.Security.Claims; |
| 19 | +using System.Text; |
| 20 | + |
| 21 | +namespace Todo.Backend.EFCore |
| 22 | +{ |
| 23 | + [Table("todos")] |
| 24 | + public class Todo { |
| 25 | + |
| 26 | + [JsonProperty("id")] |
| 27 | + [Column("id")] |
| 28 | + public int Id { get; set; } |
| 29 | + |
| 30 | + [JsonProperty("title")] |
| 31 | + [Column("todo", TypeName = "nvarchar(100)")] |
| 32 | + public string Title { get; set; } |
| 33 | + |
| 34 | + [JsonProperty("completed")] |
| 35 | + [Column("completed", TypeName = "tinyint")] |
| 36 | + public bool Completed { get; set; } |
| 37 | + |
| 38 | + [Column("owner_id", TypeName = "nvarchar(128)")] |
| 39 | + public string Owner { get; set; } |
| 40 | + |
| 41 | + public bool ShouldSerializeOwner() => false; |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + public class TodoContext : DbContext |
| 46 | + { |
| 47 | + public TodoContext(DbContextOptions<TodoContext> options) |
| 48 | + : base(options) |
| 49 | + { } |
| 50 | + |
| 51 | + protected override void OnModelCreating(ModelBuilder modelBuilder) |
| 52 | + { |
| 53 | + modelBuilder.HasSequence<int>("global_sequence"); |
| 54 | + |
| 55 | + modelBuilder.Entity<Todo>() |
| 56 | + .Property(o => o.Id) |
| 57 | + .HasDefaultValueSql("NEXT VALUE FOR global_sequence"); |
| 58 | + |
| 59 | + modelBuilder.Entity<Todo>() |
| 60 | + .Property(o => o.Owner) |
| 61 | + .HasDefaultValue("anonymous"); |
| 62 | + } |
| 63 | + |
| 64 | + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) |
| 65 | + => optionsBuilder |
| 66 | + .LogTo(Console.WriteLine, LogLevel.Information) |
| 67 | + .EnableSensitiveDataLogging() |
| 68 | + .EnableDetailedErrors(); |
| 69 | + |
| 70 | + public DbSet<Todo> Todos { get; set; } |
| 71 | + } |
| 72 | + |
| 73 | + public class TodoContextFactory: IDesignTimeDbContextFactory<TodoContext> |
| 74 | + { |
| 75 | + public TodoContext CreateDbContext(string[] args) |
| 76 | + { |
| 77 | + var optionsBuilder = new DbContextOptionsBuilder<TodoContext>(); |
| 78 | + optionsBuilder.UseSqlServer(Environment.GetEnvironmentVariable("AzureSQL")); |
| 79 | + |
| 80 | + return new TodoContext(optionsBuilder.Options); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + public class ClientPrincipal |
| 85 | + { |
| 86 | + public string IdentityProvider { get; set; } |
| 87 | + public string UserId { get; set; } |
| 88 | + public string UserDetails { get; set; } |
| 89 | + public IEnumerable<string> UserRoles { get; set; } |
| 90 | + } |
| 91 | + |
| 92 | + public static class Utils |
| 93 | + { |
| 94 | + public static ClientPrincipal ParsePrincipal(this HttpRequest req) |
| 95 | + { |
| 96 | + var principal = new ClientPrincipal(); |
| 97 | + |
| 98 | + if (req.Headers.TryGetValue("x-ms-client-principal", out var header)) |
| 99 | + { |
| 100 | + var data = header[0]; |
| 101 | + var decoded = Convert.FromBase64String(data); |
| 102 | + var json = Encoding.UTF8.GetString(decoded); |
| 103 | + principal = JsonConvert.DeserializeObject<ClientPrincipal>(json); |
| 104 | + } |
| 105 | + |
| 106 | + principal.UserRoles = principal.UserRoles?.Except(new string[] { "anonymous" }, StringComparer.CurrentCultureIgnoreCase); |
| 107 | + principal.UserId = principal.UserId ?? "anonymous"; |
| 108 | + |
| 109 | + return principal; |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + public class ToDoHandler |
| 114 | + { |
| 115 | + private TodoContext _todoContext; |
| 116 | + |
| 117 | + public ToDoHandler(TodoContext todoContext) |
| 118 | + { |
| 119 | + this._todoContext = todoContext; |
| 120 | + } |
| 121 | + |
| 122 | + [FunctionName("GetEF")] |
| 123 | + public async Task<IActionResult> Get( |
| 124 | + [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "ef/todo/{id:int?}")] HttpRequest req, |
| 125 | + ILogger log, |
| 126 | + int? id) |
| 127 | + { |
| 128 | + var cp = req.ParsePrincipal(); |
| 129 | + |
| 130 | + IQueryable<Todo> todos = this._todoContext.Todos.Where(t => t.Owner == cp.UserId); |
| 131 | + |
| 132 | + if (id.HasValue) { |
| 133 | + todos = this._todoContext.Todos.Where(t => t.Id == id); |
| 134 | + } |
| 135 | + |
| 136 | + return new OkObjectResult(await todos.ToListAsync()); |
| 137 | + } |
| 138 | + |
| 139 | + [FunctionName("PostEF")] |
| 140 | + public async Task<IActionResult> Post( |
| 141 | + [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "ef/todo")] HttpRequest req, |
| 142 | + ILogger log) |
| 143 | + { |
| 144 | + var cp = req.ParsePrincipal(); |
| 145 | + |
| 146 | + string body = await new StreamReader(req.Body).ReadToEndAsync(); |
| 147 | + var todo = JsonConvert.DeserializeObject<Todo>(body); |
| 148 | + todo.Owner = cp.UserId; |
| 149 | + |
| 150 | + await this._todoContext.AddAsync(todo); |
| 151 | + await this._todoContext.SaveChangesAsync(); |
| 152 | + |
| 153 | + var result = new List<Todo>() { todo }; |
| 154 | + return new OkObjectResult(result); |
| 155 | + } |
| 156 | + |
| 157 | + [FunctionName("PatchEF")] |
| 158 | + public async Task<IActionResult> Patch( |
| 159 | + [HttpTrigger(AuthorizationLevel.Anonymous, "patch", Route = "ef/todo/{id}")] HttpRequest req, |
| 160 | + ILogger log, |
| 161 | + int id) |
| 162 | + { |
| 163 | + var cp = req.ParsePrincipal(); |
| 164 | + |
| 165 | + string body = await new StreamReader(req.Body).ReadToEndAsync(); |
| 166 | + var newTodo = JsonConvert.DeserializeObject<Todo>(body); |
| 167 | + |
| 168 | + var targetTodo = this._todoContext.Todos.Where(t => t.Owner == cp.UserId).FirstOrDefault(t => t.Id == id); |
| 169 | + if (targetTodo == null) |
| 170 | + return new NotFoundResult(); |
| 171 | + |
| 172 | + targetTodo.Title = newTodo.Title ?? targetTodo.Title; |
| 173 | + targetTodo.Completed = newTodo.Completed; |
| 174 | + |
| 175 | + await this._todoContext.SaveChangesAsync(); |
| 176 | + |
| 177 | + return new OkObjectResult(targetTodo); |
| 178 | + } |
| 179 | + |
| 180 | + [FunctionName("DeleteEF")] |
| 181 | + public async Task<IActionResult> Delete( |
| 182 | + [HttpTrigger(AuthorizationLevel.Anonymous, "delete", Route = "ef/todo/{id}")] HttpRequest req, |
| 183 | + ILogger log, |
| 184 | + int id) |
| 185 | + { |
| 186 | + var cp = req.ParsePrincipal(); |
| 187 | + |
| 188 | + var todo = this._todoContext.Todos.Where(t => t.Owner == cp.UserId).FirstOrDefault(t => t.Id == id); |
| 189 | + |
| 190 | + if (todo == null) |
| 191 | + return new NotFoundResult(); |
| 192 | + |
| 193 | + this._todoContext.Todos.Remove(todo); |
| 194 | + await this._todoContext.SaveChangesAsync(); |
| 195 | + |
| 196 | + return new OkObjectResult(todo); |
| 197 | + } |
| 198 | + } |
| 199 | +} |
0 commit comments