<commit_before>Boards = new Mongo.Collection('board');

function boostrapAdmin(){
  // Roles.createRole("admin");
  // var userId = Accounts.createUser({ 
  //   username: "admin", 
  //   email: "<EMAIL>", 
  //   password: <PASSWORD>}", 
  //   roles: ['admin'] });
    
  // if (!userId) {
  //   return 'admin not created';
  // }
  // var adminUser = Meteor.users.findOne({ "username": "admin" });
  // Roles.addUsersToRoles(adminUser._id, "admin"); 
}
  
  // Global API configuration
  var Api = new Restivus({
    useDefaultAuth: false,
    auth: {
      user: function() {
        //TODO: check token auth first
        if (this.queryParams.token && this.queryParams.username) {
          if (this.queryParams.token !== Meteor.settings.authToken) {
            return null;
          }
          
          return { user : Meteor.users.findOne({"username": this.queryParams.username})};
        }
      }
    },
    prettyJson: true,
    onLoggedIn: function () {
      console.log(this.user.username + ' (' + this.userId + ') logged in');
    },
  });
  
  // Generates: GET, POST on /api/items and GET, PUT, DELETE on
  // /api/items/:id for the Items collection
  Api.addCollection(Boards);
  
  Api.addRoute('users/:id', { authRequired: true }, {
    get: { 
          action: function () {
              var stampedToken = Accounts._generateStampedLoginToken();
              var hashStampedToken = Accounts._hashStampedToken(stampedToken);
              
              //push resume token
              Meteor.users.update(this.userId, 
                {$push: {'services.resume.loginTokens': hashStampedToken}}
              );
              
              var when = stampedToken.when;
              
              when.setDate(when.getDate() + 365);
              return { 
                'username': this.user.username,
                'userId': this.userId,
                'token': stampedToken.token,
                'tokenExpire': when.toString()
              };
          }
      }
    });
    
  Api.addRoute('users', { authRequired: false }, {
    post: { 
      roleRequired: ['admin'],
      action: function () {
        var existingUser = Meteor.users.findOne({ "username": this.bodyParams.username });
        if (existingUser != null) {
          return { userId: existingUser._id };
        }
        
        var userId = Accounts.createUser({ username: this.bodyParams.username, email: this.bodyParams.email, password: this.bodyParams.password });
        if (userId) {
          return { userId : userId };
        }
        
        return { stausCode: 500 };  
      }
    }
  });

  Api.addRoute('boards/:id', { authRequired: true }, {
    get: function () {
      return Boards.findOne(this.urlParams.id);
    }
  });<commit_msg>Add board post api; fix other permission issues<commit_after>//This function is a copy of the Board.before.insert function of the BoardCollections in Boards.js
function getBoard(userId, doc) {
  doc.slug = doc.title;
  doc.createdAt = new Date();
  doc.archived = false;
  doc.members = doc.members || [{
    userId,
    isAdmin: true,
    isActive: true,
  }];
  doc.stars = 0;
  //Boards refers to the Boards instance from BoardCollections
  doc.color = Boards.simpleSchema()._schema.color.allowedValues[0];

  //Handle labels
  const colors = Boards.simpleSchema()._schema['labels.$.color'].allowedValues;
  const defaultLabelsColors = _.clone(colors).splice(0, 6);
  doc.labels = _.map(defaultLabelsColors, (color) => {
    return {
      color,
      _id: Random.id(6),
      name: '',
    };
  });
  
  return doc;
}
    
function boostrapAdmin(){
  // Roles.createRole("admin");
  // var userId = Accounts.createUser({ 
  //   username: "admin", 
  //   email: "<EMAIL>", 
  //   password: "{<PASSWORD>}", 
  //   roles: ['admin'] });
    
  // if (!userId) {
  //   return 'admin not created';
  // }
  // var adminUser = Meteor.users.findOne({ "username": "admin" });
  // Roles.addUsersToRoles(adminUser._id, "admin"); 
}
  
  // Global API configuration
  var Api = new Restivus({
    useDefaultAuth: false,
    auth: {
      user: function() {
        //TODO: check token auth first
        if (this.queryParams.token && this.queryParams.username) {
          if (this.queryParams.token !== Meteor.settings.authToken) {
            return null;
          }
          
          return { user : Meteor.users.findOne({"username": this.queryParams.username})};
        }
      }
    },
    prettyJson: true,
    onLoggedIn: function () {
      console.log(this.user.username + ' (' + this.userId + ') logged in');
    },
  });
  
  //users
  Api.addRoute('users/:id', { authRequired: true }, {
    get: { 
          action: function () {
              var stampedToken = Accounts._generateStampedLoginToken();
              var hashStampedToken = Accounts._hashStampedToken(stampedToken);
              
              //push resume token
              Meteor.users.update(this.userId, 
                {$push: {'services.resume.loginTokens': hashStampedToken}}
              );
              
              var when = stampedToken.when;
              
              when.setDate(when.getDate() + 365);
              return { 
                'username': this.user.username,
                'userId': this.userId,
                'token': stampedToken.token,
                'tokenExpire': when.toString()
              };
          }
      }
    });

  Api.addRoute('users', { authRequired: true }, {
    post: { 
      roleRequired: ['admin'],
      action: function () {
        var existingUser = Meteor.users.findOne({ "username": this.bodyParams.username });
        if (existingUser != null) {
          return { userId: existingUser._id };
        }
        
        var userId = Accounts.createUser({ username: this.bodyParams.username, email: this.bodyParams.email, password: this.bodyParams.password });
        if (userId) {
          return { userId : userId };
        }
        
        return { stausCode: 500, message: "Error when creating user account" };  
      }
    }
  });

  //boards
  Api.addRoute('boards', { authRequired: true }, {
    post: { 
      roleRequired: ['admin'],
      action: function () {
        var boardTitle = this.bodyParams.title;
        var username = this.bodyParams.username;
        
        if (boardTitle == null){
          return { stausCode: 404, message: "Title is requried." };
        }
        
        if (username == null){
          return { stausCode: 404, message: "Username is requried." };
        }
        
        var boardAdmin = Meteor.users.findOne({ "username": username });
        if (boardAdmin == null) {
          return { stausCode: 404, message: "User '" + username + "' does not exist" };
        }
        
        var board = Boards.findOne({ "title" : boardTitle });
        if (board != null && board._id != null) {
          return { id : board._id };
        }
        else {
            //TODO: make it work with hooks (matb33/meteor-collection-hooks) defined in Boards.js
            var boardToInsert = getBoard(boardAdmin._id, { title: boardTitle, permission: "private" });
            var boardId =  Boards.direct.insert(boardToInsert);
            return { id: boardId };
        }
        
        return { stausCode: 500, message: "Error when creating board" };  
      }
    }
  });
{'fraction_non_alphanumeric': 0.13872282608695652, 'fraction_numerical': 0.00421195652173913, 'mean_word_length': 1.9152475247524752, 'pattern_counts': {'":': 7, '<': 7, '<?xml version=': 0, '>': 8, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1154746', 'n_tokens_mistral': 2179, 'n_tokens_neox': 2138, 'n_words': 465}