   # res.cookie 'clientId', result.newToken, path : '/'
 
   # set session token for later usage down the line
-  client.sessionToken         = result.newToken
-  owner                       = result.account
-  client.connection.delegate  = result.account
+  owner                      = result.account
+  redirect                  ?= '/'
+  client.sessionToken        = result.newToken
+  client.connection.delegate = result.account
+
+  return  if validateGroupData(body, res) isnt yes
 
   JGroup.create client,
+    slug            : slug
     title           : companyName
-    slug            : slug
     visibility      : 'hidden'
-    defaultChannels : []
     initialData     : body
     allowedDomains  : convertToArray domains # clear & convert domains into array
+    defaultChannels : []
   , owner, (err, group) ->
 
     if err or not group

      # handle the request with an HTTP redirect:
      res.redirect 301, redirect


# convertToArray converts given comma separated string value into cleaned,
# trimmed, lowercased, unified array of string

module.exports = (req, res, next) ->

  { body }                       = req
  { # slug is team slug, unique name. Can not be changed
    slug
    email
    # newsletter holds announcements config.
    newsletter
    # is group creator already a member
    alreadyMember }              = body
  { JUser, JGroup, JInvitation } = koding.models

  clientId                       = getClientId req, res

  return handleClientIdNotFound res, req  unless clientId

  client              = {}
  context             = { group: slug }
  clientIPAddress     = req.headers['x-forwarded-for'] || req.connection.remoteAddress
  # parsing booling from string
  alreadyMember       = alreadyMember is 'true'
  # this function will be bound with necessary data in the queue later
  handleGroupCreation = ->

  queue = [

    ->
      koding.fetchClient clientId, context, (client_) ->

        client = client_
        # when there is an error in the fetchClient, it returns message in it
        if client.message
          console.error JSON.stringify {req, client}
          return res.status(500).send client.message

        client.clientIP = (clientIPAddress.split ',')[0]

        # subscribe to koding marketing mailings or not
        body.emailFrequency         or= {}
        # convert string boolean to boolean
        body.emailFrequency.marketing = newsletter is 'true'
        queue.next()

    ->
      # checking if group slug was already used
      JGroup.one { slug }, (err, group) ->
        return res.status(500).send 'an error occured'  if err
        return res.status(403).send "Sorry,
          Team URL '#{slug}.koding.com' is already in use"  if group
        queue.next()

    ->
      # checking if user exists by email
      JUser.one { email }, (err, user) ->
        return res.status(500).send 'an error occured'  if err
        alreadyMember = true  if user
        queue.next()

    ->
      # binding createGroup function to be used as callback in both login and convert
      handleGroupCreation = createGroup.bind null, client, req, res, body
      queue.next()

    ->
      if alreadyMember
      then JUser.login client.sessionToken, body, handleGroupCreation
      else JUser.convert client, body, handleGroupCreation

  ]

  daisy queue


createGroup = (client, req, res, body, err, result) ->

  return res.status(400).send getErrorMessage err  if err?

