示例#1
0
def createUser(emailId, displayName, jobTitle, timezone, passwd):
    localpart, domain = emailId.split("@")

    existingUser = yield db.get_count(emailId, "userAuth")
    if not existingUser:
        orgId = yield getOrgKey(domain)
        if not orgId:
            orgId = utils.getUniqueKey()
            domains = {domain:''}
            basic = {"name":domain, "type":"org"}
            yield db.batch_insert(orgId, "entities", {"basic":basic,"domains":domains})
            yield db.insert(domain, "domainOrgMap", '', orgId)

        userId = yield utils.addUser(emailId, displayName, passwd,
                                     orgId, jobTitle, timezone)
    else:
        raise Exception("User already exists for " + emailId)
示例#2
0
    def _addUser(self, request):
        emailId = utils.getRequestArg(request, 'email')
        existingUser = db.get_count(emailId, "userAuth")

        localpart, domain = emailId.split("@")
        displayName = utils.getRequestArg(request, 'name')
        jobTitle = utils.getRequestArg(request, 'jobTitle')
        timezone = utils.getRequestArg(request, 'timezone')
        passwd = utils.getRequestArg(request, 'password', sanitize=False)
        pwdrepeat = utils.getRequestArg(request, 'pwdrepeat', sanitize=False)
        if not displayName or not jobTitle or not timezone or not passwd:
            raise errors.MissingParams([_("All fields are required to create the user")])

        if passwd != pwdrepeat:
            raise PasswordsNoMatch()

        args = {'emailId': emailId, 'view': 'invite'}

        existingUser = yield existingUser
        if not existingUser:
            authinfo = yield defer.maybeDeferred(request.getSession, IAuthInfo)
            orgId = yield getOrgId(domain)
            if not orgId:
                orgId = utils.getUniqueKey()
                domains = {domain: ''}
                basic = {"name": domain, "type": "org"}
                yield db.batch_insert(orgId, "entities", {"basic": basic,
                                                          "domains": domains})
                yield db.insert(domain, "domainOrgMap", '', orgId)

            userId = yield utils.addUser(emailId, displayName, passwd,
                                         orgId, jobTitle, timezone)
            authinfo.username = userId
            authinfo.organization = orgId
            authinfo.isAdmin = False
            yield request._saveSessionToDB()

            cols = yield db.get_slice(domain, "invitations", [emailId])
            cols = utils.supercolumnsToDict(cols)

            userIds = cols.get(emailId, {}).values()
            if userIds:
                db.batch_remove({'invitationsSent': userIds}, names=[emailId])

            yield db.remove(domain, "invitations", super_column=emailId)
            t.render(request, "signup.mako", **args)

            # Notify all invitees about this user.
            token = utils.getRequestArg(request, "token")
            acceptedInvitationSender = cols.get(emailId, {}).get(token)
            otherInvitees = [x for x in userIds
                             if x not in (acceptedInvitationSender, emailId)]

            entities = base.EntitySet(userIds + [orgId, userId])
            yield entities.fetchData()
            data = {"entities": entities, 'orgId': orgId}

            yield notifications.notify([acceptedInvitationSender], ":IA", userId, **data)
            yield notifications.notify(otherInvitees, ":NU", userId, **data)
        else:
            raise InvalidRegistration("A user with this e-mail already exists! Already registered?")
示例#3
0
    def _addUsers(self, request):
        authInfo = request.getSession(IAuthInfo)
        myId = authInfo.username
        orgId = authInfo.organization
        org = base.Entity(orgId)
        yield org.fetchData(['basic', 'domains'])

        # File upload
        dataFmt = utils.getRequestArg(request, 'format')
        data = utils.getRequestArg(request, "data", sanitize=False)

        # Form submit - single user addtion
        name = utils.getRequestArg(request, "name")
        emailId = utils.getRequestArg(request, "email", sanitize=False)
        passwd = utils.getRequestArg(request, "passwd", sanitize=False)
        jobTitle = utils.getRequestArg(request, "jobTitle")
        timezone = utils.getRequestArg(request, "timezone")
        existingUsers = set()

        fileUpload = True if (dataFmt or data) else False

        if fileUpload and not (dataFmt and data):
            raise errors.MissingParams([_("File")])

        if fileUpload and dataFmt not in ('csv', 'tsv'):
            raise errors.InvalidRequest("New user details are invalid")

        if not fileUpload and not all([name, emailId, passwd, jobTitle, timezone]):
            raise errors.MissingParams([_("All fields are required to create the user")])

        if dataFmt in ("csv", "tsv"):
            dialect = csv.excel_tab  if dataFmt == "tsv" else csv.excel
            data = csv.reader(data.split("\n"), dialect=dialect)
            data = [row for row in data]
            invalidLines = self._validateData(data, orgId, org)
            if invalidLines:
                if len(invalidLines) == 1:
                    msg = "Invalid data found in line %s." % (invalidLines[0])
                elif len(invalidLines) <= 3:
                    msg = "Invalid data found in lines %s." % (",".join(invalidLines[:3]))
                else:
                    msg = "Invalid data found in lines %s and others." % (",".join(invalidLines[:3]))
                request.write("<script>parent.$$.alerts.error('%s');</script>" % (msg))
                raise errors.InvalidRequest("New user details are invalid")

        if all([name, emailId, passwd, jobTitle, timezone]):
            data = [[name, emailId, jobTitle, timezone, passwd]]
            errorFields = []
            try:
                domain = emailId.split("@")[1]
                if domain not in org.domains:
                    errorFields = ['Email']
            except IndexError:
                errorFields = ['Email']

            if not validTimezone(timezone):
                errorFields.append('Timezone')
            if errorFields:
                raise errors.InvalidRequest("Invalid %s " % (','.join(errorFields)))

        for row in data:
            if row:
                displayName, email, jobTitle, timezone, passwd = row
                existingUser = yield utils.existingUser(email)
                if existingUser:
                    log.info("%s is already a member of the network."
                            "not adding it again" % (email))
                    existingUsers.add(email)
                    continue
                yield utils.addUser(email, displayName, passwd,
                                              orgId, jobTitle, timezone)
        if not fileUpload:
            if existingUsers:
                response = """
                                $$.alerts.error('User is already in the network.');
                                $$.dialog.close('addpeople-dlg', true);

                            """
            else:
                response = """
                                $$.alerts.info('User Added');
                                $$.dialog.close('addpeople-dlg', true);
                                $$.fetchUri('/admin/people?type=all');

                            """
        else:
            response = """
                            <script>
                            parent.$$.alerts.info('Users Added');
                            parent.$$.fetchUri('/admin/people?type=all');
                            parent.$$.dialog.close('addpeople-dlg', true);
                            </script>

                        """

        request.write(response)