2015-04-01 14:56:48 -04:00
|
|
|
async = require 'async'
|
|
|
|
mongoose = require 'mongoose'
|
|
|
|
Handler = require '../commons/Handler'
|
|
|
|
Clan = require './Clan'
|
|
|
|
|
|
|
|
ClanHandler = class ClanHandler extends Handler
|
|
|
|
modelClass: Clan
|
|
|
|
jsonSchema: require '../../app/schemas/models/Clan.schema'
|
|
|
|
allowedMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']
|
|
|
|
|
|
|
|
hasAccess: (req) ->
|
|
|
|
return true if req.method in ['GET']
|
|
|
|
return true if req.user? and not req.user.isAnonymous()
|
|
|
|
false
|
|
|
|
|
|
|
|
hasAccessToDocument: (req, document, method=null) ->
|
|
|
|
method = (method or req.method).toLowerCase()
|
|
|
|
return true if req.user?.isAdmin()
|
|
|
|
return true if method is 'get'
|
|
|
|
false
|
|
|
|
|
|
|
|
makeNewInstance: (req) ->
|
2015-04-01 18:24:45 -04:00
|
|
|
userName = req.user.get('name') ? 'Anoner'
|
2015-04-01 14:56:48 -04:00
|
|
|
instance = super(req)
|
|
|
|
instance.set 'ownerID', req.user._id
|
2015-04-01 18:24:45 -04:00
|
|
|
instance.set 'ownerName', userName
|
2015-04-01 14:56:48 -04:00
|
|
|
instance.set 'members', [
|
2015-04-01 18:24:45 -04:00
|
|
|
{id: req.user._id, name: userName, level: req.user.level()}
|
2015-04-01 14:56:48 -04:00
|
|
|
]
|
|
|
|
instance
|
|
|
|
|
2015-04-01 18:24:45 -04:00
|
|
|
getByRelationship: (req, res, args...) ->
|
|
|
|
return @joinClan(req, res, args[0]) if args[1] is 'join'
|
2015-04-01 19:00:39 -04:00
|
|
|
return @leaveClan(req, res, args[0]) if args[1] is 'leave'
|
2015-04-01 18:24:45 -04:00
|
|
|
super(arguments...)
|
|
|
|
|
|
|
|
joinClan: (req, res, clanID) ->
|
|
|
|
return @sendForbiddenError(res) unless req.user? and not req.user.isAnonymous()
|
|
|
|
Clan.findById clanID, (err, clan) =>
|
|
|
|
return @sendSuccess(res, clan) if _.find clan.get('members'), (m) -> m.id.equals req.user.id
|
|
|
|
member =
|
|
|
|
id: req.user._id
|
|
|
|
name: req.user.get('name') ? 'Anoner'
|
|
|
|
level: req.user.level()
|
|
|
|
Clan.update {_id: clanID}, {$push: {members: member}}, (err) =>
|
|
|
|
return @sendDatabaseError(res, err) if err
|
|
|
|
@sendSuccess(res)
|
|
|
|
|
2015-04-01 19:00:39 -04:00
|
|
|
leaveClan: (req, res, clanID) ->
|
|
|
|
return @sendForbiddenError(res) unless req.user? and not req.user.isAnonymous()
|
|
|
|
Clan.findById clanID, (err, clan) =>
|
|
|
|
return @sendDatabaseError(res, err) if err
|
|
|
|
return @sendForbiddenError(res) if clan.get('ownerID')?.equals req.user._id
|
|
|
|
Clan.update {_id: clanID}, {$pull: {members: {id: req.user._id}}}, (err) =>
|
|
|
|
return @sendDatabaseError(res, err) if err
|
|
|
|
@sendSuccess(res)
|
|
|
|
|
2015-04-01 14:56:48 -04:00
|
|
|
module.exports = new ClanHandler()
|