コード例 #1
0
        private string get_context_info(SContext c)
        {
            string r = c.id + "," + c.kind + "," + c.name + "," + c.title + "," +
                       c.description + "," + c.extras + "," + c.site.id;

            return(r);
        }
コード例 #2
0
        private void ProcessInsertDesignIdea(int id)
        {
            TableTopDataClassesDataContext db = Configurations.GetTableTopDB();
            var designideas = from d in db.Contributions
                              where d.id == id
                              select d;

            if (designideas.Count() == 1)
            {
                Contribution di = designideas.Single <Contribution>();
                User         u  = find_user_of_contribution(di);
                Activity     a  = find_activity_of_contribution(di);
                if (u == null || a == null)
                {
                    return;
                }
                string   cid = a.technical_info.Split(new char[] { ';' })[0];
                SContext c   = server_api.GetContext(cid);
                if (c == null)
                {
                    return;
                }
                SNote note = server_api.CreateNote(u.name, "DesignIdea", di.note, c.name, di.status.ToString());
                if (note == null)
                {
                    return;
                }
                di.technical_info = note.id.ToString();
                db.SubmitChanges();
                if (RESTService.Last_Exception != null)
                {
                    this.errors.Add(RESTService.Last_Exception);
                }
            }
        }
コード例 #3
0
ファイル: VerifyModule.cs プロジェクト: xdrie/gatekeeper
        public VerifyModule(SContext serverContext) : base("/auth", serverContext)
        {
            Post <VerifyUser>("/verify/{uuid}/{code}", async(req, res) => {
                // make sure user exists
                var user = serverContext.userManager.findByUuid(req.RouteValues.As <string>("uuid"));
                if (user == null)
                {
                    res.StatusCode = (int)HttpStatusCode.NotFound;
                    return;
                }

                // check if given code matches verification, then update role
                var code = req.RouteValues.As <string>("code");
                if (user.verification == code)
                {
                    user.role = User.Role.User; // promote user
                    serverContext.userManager.updateUser(user);
                    res.StatusCode = (int)HttpStatusCode.NoContent;
                    return;
                }

                res.StatusCode = (int)HttpStatusCode.Unauthorized;
                return;
            });
        }
コード例 #4
0
        private void ProcessDeleteActivity(string info)
        {
            string   context_id = info.Split(new char[] { ';' })[0];
            SContext context    = server_api.DeleteContext(context_id);

            if (RESTService.Last_Exception != null)
            {
                this.errors.Add(RESTService.Last_Exception);
            }
        }
コード例 #5
0
ファイル: MetaModule.cs プロジェクト: xdrie/gatekeeper
        public MetaModule(SContext serverContext) : base("/meta", serverContext)
        {
            Get <GetMeta>("/", async(req, res) => {
                await res.respondSerialized(new ServerMetadata {
                    name    = SConfig.SERVER_NAME,
                    version = SConfig.VERSION,
#if DEBUG
                    development = serverContext.config.server.development
#endif
                });
            });
        }
コード例 #6
0
 public SelfModule(SContext serverContext) : base("/u", serverContext)
 {
     Get <GetMyself>("/me", async(req, res) => { await res.Negotiate(new AuthenticatedUser(currentUser)); });
     Get <GetMyGroups>("/groups", async(req, res) => {
         var user = serverContext.userManager.loadGroups(currentUser);
         await res.Negotiate(user.groups);
     });
     Get <GetMyRules>("/rules", async(req, res) => {
         var resolver = new PermissionResolver(serverContext, currentUser);
         var rules    = resolver.aggregateRules();
         await res.Negotiate(rules);
     });
 }
コード例 #7
0
        public UserDirectoryModule(SContext serverContext) : base("/u", serverContext)
        {
            Get <GetPublicUser>("/{username}", async(req, res) => {
                var user = serverContext.userManager.findByUsername(req.RouteValues.As <string>("username"));
                if (user == null || user.role == User.Role.Pending)
                {
                    res.StatusCode = (int)HttpStatusCode.NotFound;
                    return;
                }

                var publicProfile = new PublicUser(user);
                await res.respondSerialized(publicProfile);
            });
        }
コード例 #8
0
 public BeanModule(SContext serverContext) : base("/bean", serverContext)
 {
     createGet <WenEta.Request, WenEta.Response>("/weneta", async(req) => {
         return(new WenEta.Response {
             thing = req.thing,
             eta = "son",
         });
     });
     createPost <WenEta.Request, WenEta.Response>("/tweet", async(req) => {
         return(new WenEta.Response {
             thing = req.thing,
             eta = "ok",
         });
     });
 }
コード例 #9
0
        public TwoFactorSetupModule(SContext serverContext) : base("/auth", serverContext)
        {
            Get <SetupTwoFactor>("/setup2fa", async(req, res) => {
                // check if two-factor ALREADY enabled
                if (currentUser.totpEnabled)
                {
                    // otp is already enabled
                    res.StatusCode = (int)HttpStatusCode.Conflict;
                    return;
                }

                // we generate a new TOTP secret
                var seed         = StringUtils.secureRandomString(TotpProvider.TOTP_SECRET_LENGTH);
                var seedBytes    = Hasher.sha256(seed);
                currentUser.totp = seedBytes;
                serverContext.userManager.updateUser(currentUser);

                // return the seed
                await res.respondSerialized(new TotpSetupResponse {
                    secret = Convert.ToBase64String(seedBytes)
                });
                return;
            });

            Post <ConfirmTwoFactor>("/confirm2fa", async(req, res) => {
                var validatedReq = await this.validateRequest <TwoFactorConfirmRequest>(req, res);
                if (!validatedReq.isValid)
                {
                    return;
                }
                var confirmReq = validatedReq.request;

                // use TOTP provider to check code
                var provider = new TotpProvider(currentUser.totp);
                if (provider.verify(confirmReq.otpcode))
                {
                    // totp confirmed, enable totp and lock
                    serverContext.userManager.setupTotpLock(currentUser, credential.token);

                    res.StatusCode = (int)HttpStatusCode.OK;
                    return;
                }

                res.StatusCode = (int)HttpStatusCode.Unauthorized;
                return;
            });
        }
コード例 #10
0
        public void ProcessInsertActivity(int id)
        {
            TableTopDataClassesDataContext db = Configurations.GetTableTopDB();
            var activities = from d in db.Activities
                             where d.id == id
                             select d;

            if (activities.Count() == 1)
            {
                Activity di      = activities.Single <Activity>();
                SContext context = server_api.AddContext(di.name, di.description, di.avatar);
                di.technical_info = context.id.ToString() + ";" + context.extras;
                if (RESTService.Last_Exception != null)
                {
                    this.errors.Add(RESTService.Last_Exception);
                }
            }
        }
コード例 #11
0
        private void ProcessUpdateActivity(int id)
        {
            TableTopDataClassesDataContext db = Configurations.GetTableTopDB();
            var activities = from d in db.Activities
                             where d.id == id
                             select d;

            if (activities.Count() == 1)
            {
                Activity di         = activities.Single <Activity>();
                string   context_id = di.technical_info.Split(new char[] { ';' })[0];
                SContext context    = server_api.UpdateContext(context_id, di.name, di.description, di.avatar);
                if (RESTService.Last_Exception != null)
                {
                    this.errors.Add(RESTService.Last_Exception);
                }
            }
        }
コード例 #12
0
ファイル: Startup.cs プロジェクト: xdrie/gatekeeper
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCarter();

            services.AddRazorPages()
            .AddRazorRuntimeCompilation();

            services.AddDbContext <AppDbContext>(options => {
                // sqlite
                options.UseSqlite("Data Source=database.db");
            });

            var context = new SContext(services);

            // register server context
            services.AddSingleton(context);

            context.start();
        }
コード例 #13
0
 public AppAuthenticationModule(SContext serverContext) : base("/app", serverContext)
 {
     Get <GetAppToken>("/token/{appId}", async(req, res) => {
         var(authIdentity, status) = await getAppAuthentication(req, res);
         res.StatusCode            = (int)status;
         if (authIdentity != null)
         {
             await res.respondSerialized(authIdentity.token);
         }
     });
     Get <GetAppIdentity>("/login/{appId}", async(req, res) => {
         var(authIdentity, status) = await getAppAuthentication(req, res);
         res.StatusCode            = (int)status;
         if (authIdentity != null)
         {
             await res.respondSerialized(authIdentity);
         }
     });
 }
コード例 #14
0
        protected AuthenticatedModule(AccessScope minimumScope, User.Role minimumRole, string path,
                                      SContext serverContext) : base(path, serverContext)
        {
            // require authentication
            this.requiresUserAuthentication();

            this.Before += async(ctx) => {
                var usernameClaim = ctx.User.Claims.First(x => x.Type == IBearerAuthenticator.CLAIM_USERNAME);
                currentUser = serverContext.userManager.findByUsername(usernameClaim.Value);

                if (currentUser.role < minimumRole)
                {
                    // give a special code for pending users
                    if (currentUser.role == User.Role.Pending)
                    {
                        ctx.Response.StatusCode = (int)HttpStatusCode.Locked;
                    }
                    else
                    {
                        ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                    }

                    return(false);
                }

                var tokenClaim = ctx.User.Claims.First(x => x.Type == IBearerAuthenticator.CLAIM_TOKEN);
                credential = serverContext.tokenResolver.resolve(tokenClaim.Value).Value;

                // check if at least minimum scope
                if (!credential.scope.greaterThan(minimumScope))
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(false);
                }

                return(true);
            };
        }
コード例 #15
0
        protected RemoteApplicationModule(string path, SContext serverContext) : base(AccessScope.globalScope,
                                                                                      User.Role.User, path, serverContext)
        {
            this.Before += async(ctx) => {
                // verify the app secret
                var appSecret = ctx.Request.Headers[Constants.APP_SECRET_HEADER];
                if (string.IsNullOrEmpty(appSecret))
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(false);
                }

                // match the token to an app
                remoteApp = serverContext.config.apps.SingleOrDefault(x => x.name == credential.scope.app);
                if (remoteApp == null || remoteApp.secret != appSecret)
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(false);
                }

                return(true);
            };
        }
コード例 #16
0
        public GroupManagementModule(SContext serverContext) : base("/groups", serverContext)
        {
            Patch <UpdateGroups>("/update", async(req, res) => {
                var validatedReq = await this.validateRequest <UpdateGroupRequest>(req, res);
                if (!validatedReq.isValid)
                {
                    return;
                }
                var updateReq = validatedReq.request;

                // ensure all the groups exist
                foreach (var group in updateReq.groups)
                {
                    if (serverContext.config.groups.All(x => x.name != group))
                    {
                        res.StatusCode = (int)HttpStatusCode.NotFound;
                        return;
                    }
                }

                // fetch the user
                var user = serverContext.userManager.findByUuid(updateReq.userUuid);
                if (user == null)
                {
                    res.StatusCode = (int)HttpStatusCode.NotFound;
                    return;
                }

                // update their group memberships
                var updateType =
                    Enum.Parse <Group.UpdateType>(updateReq.type, true);
                foreach (var group in updateReq.groups)
                {
                    serverContext.userManager.updateGroupMembership(user.id, group, updateType);
                }
            });
        }
コード例 #17
0
ファイル: RemoteInfoModule.cs プロジェクト: xdrie/gatekeeper
 public RemoteInfoModule(SContext serverContext) : base("/remote", serverContext)
 {
     Get <RemoteGetInfo>("/",
                         async(req, res) => { await res.Negotiate(new RemoteAuthentication(getUser(), getRules())); });
     Get <RemoteGetUser>("/user", async(req, res) => { await res.Negotiate(getUser()); });
 }
コード例 #18
0
ファイル: Startup.cs プロジェクト: xdrie/gatekeeper
        public void ConfigureServices(IServiceCollection services)
        {
            // Adds services required for using options.
            services.AddOptions();

            // Adds services required for using CORS
            services.AddCors();

            // enable Razor Pages
            services.AddRazorPages()
            .AddRazorRuntimeCompilation();

            // install Carter
            services.AddCarter(options => {
                options.OpenApi.DocumentTitle = SConfig.SERVER_NAME;
                options.OpenApi.ServerUrls    = new[] { "http://localhost:5000" };
                options.OpenApi.Securities    = new Dictionary <string, OpenApiSecurity> {
                    {
                        GateApiConstants.Security.USER_BEARER_AUTH,
                        new OpenApiSecurity {
                            Type = OpenApiSecurityType.http, Scheme = "bearer"
                        }
                    }, {
                        GateApiConstants.Security.REMOTE_APP_APIKEY,
                        new OpenApiSecurity
                        {
                            Type = OpenApiSecurityType.apiKey, In = OpenApiIn.header, Name = "X-App-Secret"
                        }
                    },
                    // { "ApiKey", new OpenApiSecurity { Type = OpenApiSecurityType.apiKey, Name = "X-API-KEY", In = OpenApiIn.header } }
                };
                options.OpenApi.GlobalSecurityDefinitions = new[] {
                    GateApiConstants.Security.USER_BEARER_AUTH,
                    GateApiConstants.Security.REMOTE_APP_APIKEY
                };
            });

            var serverConfig     = default(SConfig);
            var configDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(SConfig));

            if (configDescriptor == null)
            {
                // load configuration
                serverConfig = new SConfig(); // default configuration
                if (File.Exists(CONFIG_FILE))
                {
                    var configTxt = File.ReadAllText(CONFIG_FILE);
                    serverConfig.load(configTxt);
                }
            }
            else
            {
                serverConfig = (SConfig)configDescriptor.ImplementationInstance;
            }

            var context = new SContext(services, serverConfig);

            // register server context
            services.AddSingleton(context);

            // set up database
            services.AddDbContext <AppDbContext>(options => {
                switch (serverConfig.server.databaseBackend)
                {
                case SConfig.Server.DatabaseBackend.InMemory:
                    options.UseInMemoryDatabase(context.config.server.databaseConnection);
                    break;

                case SConfig.Server.DatabaseBackend.Sqlite:
                    options.UseSqlite(context.config.server.databaseConnection);
                    break;

                case SConfig.Server.DatabaseBackend.Postgres:
                    options.UseNpgsql(context.config.server.databaseConnection);
                    break;
                }
                if (context.config.logging.databaseLogging)
                {
                    options.EnableDetailedErrors();
                    options.EnableSensitiveDataLogging();
                }
            });

            // server context start signal
            context.start();
        }
コード例 #19
0
 protected AuthenticatedUserModule(string path, SContext serverContext) : base(AccessScope.rootScope,
                                                                               User.Role.User, path, serverContext)
 {
 }
コード例 #20
0
 protected AdminModule(string path, SContext serverContext) : base(AccessScope.rootScope,
                                                                   User.Role.Admin, path, serverContext)
 {
 }
コード例 #21
0
ファイル: AppBootstrapper.cs プロジェクト: 0xFireball/AuthN
 public AppBootstrapper(SContext context)
 {
     serverContext = context;
 }
コード例 #22
0
        //  private readonly IMapper _mapper; IMapper mapper

        public TeachersController(ISRepository repo, SContext context)
        {
            _repo    = repo;
            _context = context;
            //  _mapper = mapper;
        }
コード例 #23
0
ファイル: AuthModule.cs プロジェクト: xdrie/gatekeeper
        public AuthModule(SContext context) : base("/auth", context)
        {
            Post <CreateUser>("/create", async(req, res) => {
                var validatedCreateReq = await this.validateRequest <RegisterRequest>(req, res);
                if (!validatedCreateReq.isValid)
                {
                    return;
                }
                var createReq = validatedCreateReq.request;

                // attempt to register user
                try {
                    // register the user
                    var user = serverContext.userManager.registerUser(createReq);
                    serverContext.log.writeLine($"registered user {user.username}",
                                                Logger.Verbosity.Information);
                    var token = serverContext.userManager.issueRootToken(user.id);

                    // Return user details
                    res.StatusCode = (int)HttpStatusCode.Created;
                    await res.respondSerialized(new AuthedUserResponse {
                        user  = new AuthenticatedUser(user),
                        token = token
                    });
                }
                catch (UserManagerService.UserAlreadyExistsException) {
                    res.StatusCode = (int)HttpStatusCode.Conflict;
                    return;
                }
            });

            Post <LoginUser>("/login", async(req, res) => {
                var login = await validateAndCheckPassword <LoginRequest>(req, res);
                if (login.isValid)
                {
                    // check two-factor
                    if (login.user.totpEnabled)
                    {
                        // require login with otp code, but creds were good
                        res.StatusCode = (int)HttpStatusCode.FailedDependency;
                        return;
                    }

                    // issue a new token
                    var token = serverContext.userManager.issueRootToken(login.user.id);

                    // return user details
                    res.StatusCode = (int)HttpStatusCode.OK;
                    await res.respondSerialized(new AuthedUserResponse {
                        user  = new AuthenticatedUser(login.user),
                        token = token
                    });
                }
            });

            Post <LoginTwoFactor>("/login2fa", async(req, res) => {
                var login = await validateAndCheckPassword <LoginRequestTwoFactor>(req, res);
                if (login.isValid)
                {
                    // this route is not to be used unless two factor is enabled
                    if (!login.user.totpEnabled)
                    {
                        res.StatusCode = (int)HttpStatusCode.PreconditionFailed;
                        return;
                    }

                    // use TOTP provider to check code
                    var provider = new TotpProvider(login.user.totp);
                    if (!provider.verify(login.request.otpcode))
                    {
                        res.StatusCode = (int)HttpStatusCode.Unauthorized;
                        return;
                    }

                    // issue a new token
                    var token = serverContext.userManager.issueRootToken(login.user.id);

                    // return user details
                    res.StatusCode = (int)HttpStatusCode.OK;
                    await res.respondSerialized(new AuthedUserResponse {
                        user  = new AuthenticatedUser(login.user),
                        token = token
                    });
                }
            });

            Post <DeleteUser>("/delete", async(req, res) => {
                var login = await validateAndCheckPassword <LoginRequest>(req, res);
                if (login.isValid)
                {
                    // delete the account
                    serverContext.userManager.deleteUser(login.user.id);
                    // return success indication
                    res.StatusCode = (int)HttpStatusCode.NoContent;
                    return;
                }
            });
        }
コード例 #24
0
 protected UnverifiedUserModule(string path, SContext serverContext) : base(AccessScope.rootScope,
                                                                            User.Role.Pending, path, serverContext)
 {
 }
コード例 #25
0
 public CourseController(SContext context)
 {
     this.db        = context;
     MysqlClient.DB = context;
 }
コード例 #26
0
 //Quartz.net doesn't appear to like that I'm injecting these,
 //because if I remove this parameter, execute...executes.
 public ImportJob(SContext db)
 {
     _db = db;
 }