Пример #1
0
        protected override SirenEntityBuilder AddCollectionActions(
            SirenEntityBuilder entity)
        {
            Claim c = Context.HttpContext.User.FindFirst(ClaimTypes.Role);

            if (c != null && (c.Value.Equals(Roles.Admin) || c.Value.Equals(Roles.Teacher)))
            {
                entity
                .WithAction(new ActionBuilder()
                            .WithName("add-student-to-class")
                            .WithTitle("Add Student To Class")
                            .WithMethod("POST")
                            .WithHref(Url.AbsoluteRouteUrl(
                                          Routes.ClassParticipantAdd,
                                          new { id = Identifier })
                                      )
                            .WithType("application/json")
                            .WithField(new FieldBuilder()
                                       .WithTitle("Number")
                                       .WithName("number")
                                       .WithType("number")));
            }

            return(entity);
        }
Пример #2
0
        public ActionResult Receive(ILinkback linkback, int id)
        {
            Uri target_url = linkback is Pingback ? null : new Uri(Url.AbsoluteRouteUrl("Post", new { id }));

            IReceiveResult context = linkback.Receive(Request, target_url);

            if (context.Valid)
            {
                var comment = new Comment
                {
                    Created = DateTime.Now,
                    From    = String.Format("{0} from {1}", linkback.Name, context.Url),
                    Content = context.Excerpt ?? context.Title
                };

                if (linkback is Pingback)
                {
                    id = Int32.Parse(context.TargetUri.ToString().Substring(context.TargetUri.ToString().LastIndexOf("/") + 1));
                }

                var post = _db.Post.First(x => x.Id == id);
                post.Comments.Add(comment);
                _db.SaveChanges();
            }

            linkback.SendResponse(Response);

            return(new EmptyResult());
        }
Пример #3
0
        public ActionResult Send(ILinkback linkback, int id, string url, bool?autodiscovery)
        {
            var post = _db.Post.First(x => x.Id == id);

            string source_url = Url.AbsoluteRouteUrl("Post", new { id });

            var parameters = new LinkbackSendParameters
            {
                // Trackback
                Title         = post.Title,
                Excerpt       = post.Content,
                Url           = new Uri(source_url),
                BlogName      = "Linkback.NET Demo",
                AutoDiscovery = autodiscovery,

                // Linkback
                SourceUrl = new Uri(source_url),
                TargetUrl = new Uri(url)
            };

            var result = linkback.Send(new Uri(url), parameters);

            TempData["Linkback-Send-Result"] = result.Success
                ? String.Format("{0} for {1} sent", linkback.Name, url)
                : String.Format("Error: {0}({1})", result.Message, result.Code);

            return(RedirectToRoute(String.Format("{0}-Send", linkback.Name), new { id }));
        }
Пример #4
0
 protected override SirenEntityBuilder AddEntityLinks(SirenEntityBuilder entity, Group item)
 {
     return(entity
            .WithLink(new LinkBuilder()
                      .WithRel("self")
                      .WithHref(Url.AbsoluteRouteUrl(Routes.GroupEntry, item.Id))));
 }
Пример #5
0
 protected override SirenEntityBuilder AddEntityLinks(SirenEntityBuilder entity, Semester item)
 {
     return(entity
            .WithLink(new LinkBuilder()
                      .WithRel("self")
                      .WithHref(Url.AbsoluteRouteUrl(Routes.SemesterEntry, new { Id = item.Id }))));
 }
Пример #6
0
        //
        // GET: /Post/Details/5

        public ActionResult Details(int id)
        {
            LinkbackNet.Pingback.DeclareServiceInHttpHeader(Response, new Uri(Url.AbsoluteRouteUrl("Pingback-Receive", new { })));

            var post = _db.Post.Include("Comments").First(x => x.Id == id);

            return(View(post));
        }
Пример #7
0
        public ActionResult Search(string query)
        {
            // You can implement a proper search function here and add a Search.cshtml page.
            // return this.View(HomeControllerAction.Search);

            // Or you could use Google Custom Search (https://cse.google.com/cse) to index your site and display your
            // search results in your own page.

            // For simplicity we are just assuming your site is indexed on Google and redirecting to it.
            return(Redirect(string.Format("https://www.google.com/?q=site:{0} {1}", Url.AbsoluteRouteUrl(HomeControllerRoute.GetIndex), query)));
        }
Пример #8
0
 protected override SirenEntityBuilder AddCollectionLinks(
     SirenEntityBuilder entity)
 {
     return(entity
            .WithLink(new LinkBuilder()
                      .WithRel("self")
                      .WithHref(Url.AbsoluteRouteUrl(RouteList, new { id = Identifier })))
            .WithLink(new LinkBuilder()
                      .WithRel("index")
                      .WithHref(UrlTo(Routes.Index))));
 }
Пример #9
0
 private string GenerateLinkToListPage(
     string listRoute,
     ListQueryStringDto query,
     int pageOffset = 0)
 {
     return(Url.AbsoluteRouteUrl(listRoute,
                                 new {
         page = query.Page + pageOffset,
         limit = query.Limit,
         search = query.Search
     }));
 }
Пример #10
0
        public object Get()
        {
            var feedInfo = new
            {
                Version   = "3.0.0",
                Resources = new List <NuGetPackageResourceModel>()
                {
                    new NuGetPackageResourceModel("PackagePublish/2.0.0", Url.AbsoluteRouteUrl("upload"))
                }
            };

            return(feedInfo);
        }
Пример #11
0
 protected override SirenEntityBuilder AddEntityLinks(SirenEntityBuilder entity, Teacher item)
 {
     return(entity
            .WithLink(new LinkBuilder()
                      .WithRel("self")
                      .WithHref(Url.ToTeacher(Routes.TeacherEntry, item.Number)))
            .WithLink(new LinkBuilder()
                      .WithRel(SirenData.REL_TEACHERS_CLASSES)
                      .WithHref(Url.ToTeacher(Routes.TeacherClassList, item.Number)))
            .WithLink(new LinkBuilder()
                      .WithRel(SirenData.REL_TEACHER_COURSES)
                      .WithHref(Url.AbsoluteRouteUrl(
                                    Routes.TeacherCourseList,
                                    new { number = item.Number }))
                      ));
 }
Пример #12
0
 protected override SirenEntityBuilder AddEntityLinks(SirenEntityBuilder entity, Class item)
 {
     return(entity
            .WithLink(new LinkBuilder()
                      .WithRel("self")
                      .WithHref(Url.ToClass(Routes.ClassEntry, item.Id)))
            .WithLink(new LinkBuilder()
                      .WithRel(SirenData.REL_CLASS_TEACHERS)
                      .WithHref(Url.AbsoluteRouteUrl(
                                    Routes.ClassTeachersList, new { id = item.Id })))
            .WithLink(new LinkBuilder()
                      .WithRel(SirenData.REL_CLASS_STUDENTS)
                      .WithHref(Url.AbsoluteRouteUrl(
                                    Routes.ClassStudentsList, new { id = item.Id })))
            .WithLink(new LinkBuilder()
                      .WithRel(SirenData.REL_CLASS_GROUPS)
                      .WithHref(Url.AbsoluteRouteUrl(
                                    Routes.ClassGroupsList, new { id = item.Id }))
                      ));
 }
Пример #13
0
        /*
         |-----------------------------------------------------------------------
         | Entity
         |-----------------------------------------------------------------------
         */

        protected override SirenEntityBuilder AddEntityActions(SirenEntityBuilder entity, Group item)
        {
            Claim c = Context.HttpContext.User.FindFirst(ClaimTypes.Role);

            if (c != null && (c.Value.Equals(Roles.Admin) || c.Value.Equals(Roles.Teacher)))
            {
                entity.WithAction(new ActionBuilder()
                                  .WithName("delete-group")
                                  .WithTitle("Delete Group")
                                  .WithMethod("Delete")
                                  .WithHref(
                                      Url.AbsoluteRouteUrl(
                                          Routes.GroupDelete,
                                          new { id = item.Id }
                                          )
                                      ));
            }

            return(entity);
        }
Пример #14
0
        protected override SirenEntityBuilder AddEntityActions(SirenEntityBuilder entity, Teacher item)
        {
            Claim c = Context.HttpContext.User.FindFirst(ClaimTypes.Role);

            if (c != null && (c.Value.Equals(Roles.Admin) || c.Value.Equals(Roles.Teacher)))
            {
                entity
                .WithAction(
                    new ActionBuilder()
                    .WithName("remove-teacher-from-class")
                    .WithTitle("Remove Teacher from Class")
                    .WithMethod("DELETE")
                    .WithHref(Url.AbsoluteRouteUrl(
                                  Routes.ClassTeacherRemove,
                                  new { id = Identifier, teacherId = item.Number }
                                  ))
                    );
            }

            return(entity);
        }
Пример #15
0
        public IActionResult Login([FromQuery] string success,
                                   [FromQuery] string?failure  = null,
                                   [FromQuery] string?userData = null)
        {
            var req = new OauthLoginRequest(githubAuthSettings.ClientId)
            {
                State = new StateData
                {
                    RandomState     = CurrentRandomData,
                    SuccessCallback = success,
                    FailureCallback = failure,
                    UserData        = userData
                }.Encrypt(stateEncAlgo),
                AllowSignup = false,
                RedirectUri = new Uri(Url.AbsoluteRouteUrl(LoginCallbackName))
            };

            foreach (var scope in githubAuthSettings.OauthScopes)
            {
                req.Scopes.Add(scope);
            }

            return(Ok(new { AuthTarget = client.Oauth.GetGitHubLoginUrl(req) }));
        }
Пример #16
0
 public object GetRoutes()
 => new {
     Routes = Url.AbsoluteRouteUrl(RoutesName),
     Users  = UsersController.PublicRoutes(Url)
 };
Пример #17
0
        public async Task <IActionResult> LoginComplete([FromQuery] string code, [FromQuery] string state)
        {
            const string UserDataParam = "data";
            const string SuccessParam  = "successful";
            const string ErrorParam    = "error";
            const string CodeParam     = "code";

            var stateDe = StateData.Decrypt(stateEncAlgo, state);

            if (!stateDe.IsValid)
            {
                // state invalid; refuse to brew coffee
                return(this.ImATeapot());
            }

            var successCb = stateDe.SuccessCallback;

            if (stateDe.UserData != null)
            {
                successCb = QueryHelpers.AddQueryString(successCb, UserDataParam, stateDe.UserData);
            }

            var failureCb = stateDe.FailureCallback;

            if (failureCb != null && stateDe.UserData != null)
            {
                failureCb = QueryHelpers.AddQueryString(failureCb, UserDataParam, stateDe.UserData);
            }
            else if (failureCb == null)
            {
                failureCb = QueryHelpers.AddQueryString(successCb, SuccessParam, "false");
                successCb = QueryHelpers.AddQueryString(successCb, SuccessParam, "true");
            }

            OauthToken token;

            try
            {
                token = await client.Oauth.CreateAccessToken(
                    new OauthTokenRequest(githubAuthSettings.ClientId,
                                          githubAuthSettings.ClientSecret, code)
                {
                    RedirectUri = new Uri(Url.AbsoluteRouteUrl(LoginCallbackName))
                });
            } // will not catch NotFound, Validation, or LegalRestriction because those are hard errors
            catch (AuthorizationException e)
            {
                return(Redirect(QueryHelpers.AddQueryString(failureCb, ErrorParam,
                                                            $"GitHub returned Unauthorized: {e.Message}")));
            }
            catch (ForbiddenException e)
            {
                return(Redirect(QueryHelpers.AddQueryString(failureCb, ErrorParam,
                                                            $"GitHub returned Forbidden: {e.Message}")));
            }
            catch (ApiException e)
            {
                return(Redirect(QueryHelpers.AddQueryString(failureCb, ErrorParam,
                                                            $"GitHub returned error: {e.Message}")));
            }

            if (token.TokenType != "bearer") // don't know what to do with it
            {
                return(Redirect(QueryHelpers.AddQueryString(failureCb, ErrorParam,
                                                            $"API returned unknown token type {token.TokenType}")));
            }

            var newCode = Utils.GetCryptoRandomHexString(8);                     // keep it somewhat short

            while (await repoContext.AuthCodes.AnyAsync(s => s.Code == newCode)) // in the odd case that 2 exist at once
            {
                newCode = Utils.GetCryptoRandomHexString(8);
            }

            repoContext.AuthCodes.Add(new AuthCodeTempStore
            {
                Code         = newCode,
                GitHubBearer = token.AccessToken
            });

            await repoContext.SaveChangesAsync(); // these saves feel kinda gross ngl

            // TODO: will this ever cause a race condition?

            return(Redirect(QueryHelpers.AddQueryString(successCb, CodeParam, newCode)));
        }
Пример #18
0
        protected override SirenEntityBuilder AddEntityActions(SirenEntityBuilder entity, Class item)
        {
            Claim c = Context.HttpContext.User.FindFirst(ClaimTypes.Role);

            if (c != null && c.Value.Equals(Roles.Admin))
            {
                entity
                .WithAction(
                    new ActionBuilder()
                    .WithName("edit-class")
                    .WithTitle("Edit Class")
                    .WithMethod("PUT")
                    .WithHref(Url.ToClass(Routes.ClassEdit, item.Id))
                    .WithType("application/json")
                    .WithField(
                        new FieldBuilder()
                        .WithTitle("Name")
                        .WithName("name")
                        .WithType("text")
                        .WithValue(item.Name))
                    .WithField(
                        new FieldBuilder()
                        .WithTitle("Max Group Size")
                        .WithName("maxGroupSize")
                        .WithType("number")
                        .WithValue(item.MaxGroupSize.ToString()))
                    .WithField(
                        new FieldBuilder()
                        .WithTitle("Auto Enrollment")
                        .WithName("autoEnrollment")
                        .WithType("checkbox")
                        .WithValue(item.AutoEnrollment.ToString())))
                .WithAction(
                    new ActionBuilder()
                    .WithName("delete-class")
                    .WithTitle("Delete Class")
                    .WithMethod("DELETE")
                    .WithHref(Url.ToClass(Routes.CourseDelete, item.Id)))
                .WithAction(
                    new ActionBuilder()
                    .WithName("add-teacher-to-class")
                    .WithTitle("Add Teacher to Class")
                    .WithMethod("POST")
                    .WithHref(
                        Url.AbsoluteRouteUrl(
                            Routes.ClassTeacherAdd, new { id = item.Id }
                            )
                        )
                    .WithType("application/json")
                    .WithField(new FieldBuilder()
                               .WithTitle("Number")
                               .WithName("number")
                               .WithType("text")));
                // .WithAction(new ActionBuilder()
                //         .WithName("remove-teacher-from-class")
                //         .WithTitle("Remove Teacher from Class")
                //         .WithMethod("DELETE")
                //         .WithHref(
                //             Url.AbsoluteRouteUrl(
                //                 Routes.ClassTeacherRemove, new {id = item.Id, teacherId = }
                //             )
                //         )
                //         .WithType("application/json")
                //         .WithField(new FieldBuilder()
                //             .WithTitle("Number")
                //             .WithName("number")
                //             .WithType("text"))
                // );
            }

            return(entity);
        }