예제 #1
0
        public AdminTasksController(IDAFactory daFactory, JWTFactory jwt, IGluonHostPool hostPool) : base("/admin")
        {
            JWTTokenAuthentication.Enable(this, jwt);

            Get["/tasks"] = _ =>
            {
                this.DemandAdmin();

                using (var da = daFactory.Get)
                {
                    var offset = Request.Query["offset"];
                    var limit  = Request.Query["limit"];

                    if (offset == null)
                    {
                        offset = 0;
                    }
                    if (limit == null)
                    {
                        limit = 20;
                    }

                    if (limit > 100)
                    {
                        limit = 100;
                    }

                    var result = da.Tasks.All((int)offset, (int)limit);
                    return(Response.AsPagedList(result));
                }
            };

            Post["/tasks/request"] = x =>
            {
                var task = this.Bind <TaskRequest>();

                var taskServer = hostPool.GetByRole(Database.DA.Hosts.DbHostRole.task).FirstOrDefault();
                if (taskServer == null)
                {
                    return(Response.AsJson(-1));
                }
                else
                {
                    try {
                        var id = taskServer.Call(new RequestTask()
                        {
                            TaskType      = task.task_type.ToString(),
                            ParameterJson = JsonConvert.SerializeObject(task.parameter),
                            ShardId       = (task.shard_id == null || !task.shard_id.HasValue) ? -1 : task.shard_id.Value
                        }).Result;
                        return(Response.AsJson(id));
                    }catch (Exception ex)
                    {
                        return(Response.AsJson(-1));
                    }
                }
            };
        }
예제 #2
0
        public AdminShardsController(IDAFactory daFactory, JWTFactory jwt) : base("/admin")
        {
            JWTTokenAuthentication.Enable(this, jwt);

            this.Get["/shards"] = _ =>
            {
                this.DemandAdmin();

                using (var db = daFactory.Get())
                {
                    var shards = db.Shards.All();
                    return(Response.AsJson(shards));
                }
            };
        }
예제 #3
0
        public AdminHostsController(IDAFactory daFactory, JWTFactory jwt, IGluonHostPool hostPool) : base("/admin")
        {
            JWTTokenAuthentication.Enable(this, jwt);

            this.Get["/hosts"] = _ =>
            {
                this.DemandAdmin();
                var hosts = hostPool.GetAll();

                return(Response.AsJson(hosts.Select(x => new {
                    role = x.Role,
                    call_sign = x.CallSign,
                    internal_host = x.InternalHost,
                    public_host = x.PublicHost,
                    connected = x.Connected,
                    time_boot = x.BootTime
                })));
            };
        }
        public AdminShardOpController(IDAFactory daFactory, JWTFactory jwt, ApiServer server) : base("/admin/shards")
        {
            JWTTokenAuthentication.Enable(this, jwt);

            DAFactory = daFactory;
            Server    = server;

            After.AddItemToEndOfPipeline(x =>
            {
                x.Response.WithHeader("Access-Control-Allow-Origin", "*");
            });

            Post["/shutdown"] = _ =>
            {
                this.DemandAdmin();
                var shutdown = this.Bind <ShutdownModel>();

                var type = ShutdownType.SHUTDOWN;
                if (shutdown.update)
                {
                    type = ShutdownType.UPDATE;
                }
                else if (shutdown.restart)
                {
                    type = ShutdownType.RESTART;
                }

                //JWTUserIdentity user = (JWTUserIdentity)this.Context.CurrentUser;
                Server.RequestShutdown((uint)shutdown.timeout, type);

                return(Response.AsJson(true));
            };

            Post["/announce"] = _ =>
            {
                this.DemandModerator();
                var announce = this.Bind <AnnouncementModel>();

                Server.BroadcastMessage(announce.sender, announce.subject, announce.message);

                return(Response.AsJson(true));
            };
        }
        public RegistrationController(IDAFactory daFactory, JWTFactory jwt, ApiServerConfiguration config) : base("/userapi/registration")
        {
            JWTTokenAuthentication.Enable(this, jwt);

            DAFactory = daFactory;

            After.AddItemToEndOfPipeline(x =>
            {
                x.Response.WithHeader("Access-Control-Allow-Origin", "*");
            });

            //Create a new user
            Post["/"] = x =>
            {
                var user  = this.Bind <RegistrationModel>();
                var tryIP = Request.Headers["X-Forwarded-For"].FirstOrDefault();
                if (tryIP != null)
                {
                    tryIP = tryIP.Substring(tryIP.LastIndexOf(',') + 1).Trim();
                }
                var ip = tryIP ?? Request.UserHostAddress;

                user.username = user.username ?? "";
                user.username = user.username.ToLowerInvariant();
                user.email    = user.email ?? "";
                user.key      = user.key ?? "";
                string failReason = null;
                if (user.username.Length < 3)
                {
                    failReason = "user_short";
                }
                else if (user.username.Length > 24)
                {
                    failReason = "user_long";
                }
                else if (!USERNAME_VALIDATION.IsMatch(user.username ?? ""))
                {
                    failReason = "user_invalid";
                }
                else if ((user.password?.Length ?? 0) == 0)
                {
                    failReason = "pass_required";
                }

                if (failReason != null)
                {
                    return(Response.AsJson(new RegistrationError()
                    {
                        error = "bad_request",
                        error_description = failReason
                    }));
                }

                bool isAdmin = false;
                if (config.Regkey != null && config.Regkey != user.key)
                {
                    return(Response.AsJson(new RegistrationError()
                    {
                        error = "key_wrong",
                        error_description = failReason
                    }));
                }

                var passhash = PasswordHasher.Hash(user.password);

                using (var da = daFactory.Get)
                {
                    //has this ip been banned?
                    var ban = da.Bans.GetByIP(ip);
                    if (ban != null)
                    {
                        return(Response.AsJson(new RegistrationError()
                        {
                            error = "registration_failed",
                            error_description = "ip_banned"
                        }));
                    }

                    //has this user registered a new account too soon after their last?
                    var now  = Epoch.Now;
                    var prev = da.Users.GetByRegisterIP(ip);
                    if (now - (prev.FirstOrDefault()?.register_date ?? 0) < REGISTER_THROTTLE_SECS)
                    {
                        //cannot create a new account this soon.
                        return(Response.AsJson(new RegistrationError()
                        {
                            error = "registration_failed",
                            error_description = "registrations_too_frequent"
                        }));
                    }

                    //TODO: is this ip banned?

                    var userModel = new User
                    {
                        username      = user.username,
                        email         = user.email,
                        is_admin      = isAdmin,
                        is_moderator  = isAdmin,
                        user_state    = UserState.valid,
                        register_date = now,
                        is_banned     = false,
                        register_ip   = ip,
                        last_ip       = ip
                    };

                    var authSettings = new UserAuthenticate
                    {
                        scheme_class = passhash.scheme,
                        data         = passhash.data
                    };

                    try
                    {
                        var userId = da.Users.Create(userModel);
                        authSettings.user_id = userId;
                        da.Users.CreateAuth(authSettings);

                        userModel = da.Users.GetById(userId);
                        if (userModel == null)
                        {
                            throw new Exception("Unable to find user");
                        }
                        return(Response.AsJson(userModel));
                    } catch (Exception)
                    {
                        return(Response.AsJson(new RegistrationError()
                        {
                            error = "registration_failed",
                            error_description = "user_exists"
                        }));
                    }
                }
            };
        }
예제 #6
0
        public AdminUsersController(IDAFactory daFactory, JWTFactory jwt) : base("/admin")
        {
            JWTTokenAuthentication.Enable(this, jwt);

            this.DAFactory = daFactory;

            this.After.AddItemToEndOfPipeline(x =>
            {
                x.Response.WithHeader("Access-Control-Allow-Origin", "*");
            });

            //Get information about me, useful for the admin user interface to disable UI based on who you login as
            this.Get["/users/current"] = _ =>
            {
                this.RequiresAuthentication();
                JWTUserIdentity user = (JWTUserIdentity)this.Context.CurrentUser;

                using (var da = daFactory.Get())
                {
                    var userModel = da.Users.GetById(user.UserID);
                    if (userModel == null)
                    {
                        throw new Exception("Unable to find user");
                    }
                    return(Response.AsJson <User>(userModel));
                }
            };

            //Get the attributes of a specific user
            this.Get["/users/{id}"] = parameters =>
            {
                this.DemandModerator();

                using (var da = daFactory.Get())
                {
                    var userModel = da.Users.GetById((uint)parameters.id);
                    if (userModel == null)
                    {
                        throw new Exception("Unable to find user");
                    }
                    return(Response.AsJson <User>(userModel));
                }
            };

            //List users
            this.Get["/users"] = _ =>
            {
                this.DemandModerator();
                using (var da = daFactory.Get())
                {
                    var offset = this.Request.Query["offset"];
                    var limit  = this.Request.Query["limit"];

                    if (offset == null)
                    {
                        offset = 0;
                    }
                    if (limit == null)
                    {
                        limit = 20;
                    }

                    if (limit > 100)
                    {
                        limit = 100;
                    }

                    var result = da.Users.All((int)offset, (int)limit);
                    return(Response.AsPagedList <User>(result));
                }
            };

            //Create a new user
            this.Post["/users"] = x =>
            {
                this.DemandModerator();
                var user = this.Bind <UserCreateModel>();

                if (user.is_admin)
                {
                    //I need admin claim to do this
                    this.DemandAdmin();
                }

                using (var da = daFactory.Get())
                {
                    var userModel = new User();
                    userModel.username      = user.username;
                    userModel.email         = user.email;
                    userModel.is_admin      = user.is_admin;
                    userModel.is_moderator  = user.is_moderator;
                    userModel.user_state    = UserState.valid;
                    userModel.register_date = Epoch.Now;
                    userModel.is_banned     = false;

                    var userId = da.Users.Create(userModel);

                    userModel = da.Users.GetById(userId);
                    if (userModel == null)
                    {
                        throw new Exception("Unable to find user");
                    }
                    return(Response.AsJson <User>(userModel));
                }

                return(null);
            };
        }