<commit_before>/*
 * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package rundeck.controllers

import com.dtolabs.rundeck.core.authentication.tokens.AuthTokenType
import com.dtolabs.rundeck.core.authorization.AuthContext
import com.dtolabs.rundeck.core.authorization.UserAndRolesAuthContext
import com.dtolabs.rundeck.server.authorization.AuthConstants
import grails.converters.JSON
import grails.core.GrailsApplication
import org.rundeck.util.Sizes
import rundeck.AuthToken
import rundeck.Execution
import rundeck.User
import com.dtolabs.rundeck.app.api.ApiVersions
import rundeck.services.FrameworkService
import rundeck.services.UserService

import javax.servlet.http.HttpServletResponse

class UserController extends ControllerBase{

    private static final int DEFAULT_TOKEN_PAGE_SIZE = 50

    UserService userService
    FrameworkService frameworkService
    GrailsApplication grailsApplication
    def apiService
    def configurationService

    static allowedMethods = [
            addFilterPref      : 'POST',
            store              : 'POST',
            update             : 'POST',
            clearApiToken      : 'POST',
            generateUserToken  : 'POST',
            renderUsertoken    : 'POST',
            removeExpiredTokens: 'POST',
            apiUserData        : ['GET','POST'],
            apiUserList        : 'GET'
    ]

    def index = {
        redirect(action:"login")
    }

    def error = {
        flash.loginerror = message(code: "invalid.username.and.password")
        return render(view:'login')
    }

    def logout = {
        session.invalidate()
        return redirect(action: 'loggedout')
    }

    def loggedout(){
        if(grailsApplication.config.rundeck.security.authorization.preauthenticated.redirectLogout in ['true',true]) {
            return redirect(url: grailsApplication.config.grails.serverURL + grailsApplication.config.rundeck.security.authorization.preauthenticated.redirectUrl)
        }
    }

    def login = {
        if (session.user) {
            redirect(controller:'menu', action:'index')
        }
    }

    def denied={
        response.setStatus(403)
        renderErrorView('Access denied')
    }
    def deniedFragment={
        response.setStatus(403)
        renderErrorFragment('Access denied')
    }
    def list={
        AuthContext authContext = frameworkService.getAuthContextForSubject(session.subject)
        if(unauthorizedResponse(frameworkService.authorizeApplicationResourceType(authContext, AuthConstants.TYPE_USER,
                AuthConstants.ACTION_ADMIN),
                AuthConstants.ACTION_ADMIN, 'User', 'accounts')) {
            return
        }
        [users:User.listOrderByLogin()]
    }

    def profile() {
        //check auth to view profile
        //default to current user profile
        if (!params.login) {
            params.login = session.user
        }
        UserAndRolesAuthContext authContext = frameworkService.getAuthContextForSubject(session.subject)

        def tokenAdmin = frameworkService.authorizeApplicationResourceType(
                authContext,
                AuthConstants.TYPE_USER,
                AuthConstants.ACTION_ADMIN)

        if (unauthorizedResponse(
                params.login == session.user || tokenAdmin,
                AuthConstants.ACTION_ADMIN, 'Users', params.login)) {
            return
        }

        def User u = User.findByLogin(params.login)
        if (!u && params.login == session.user) {
            //redirect to profile edit page, so user can setup their profile
            flash.message = "Please fill out your profile"
            return redirect(action: 'register')
        }
        if (notFoundResponse(u, 'User', params['login'])) {
            return
        }

        def tokenTotal = AuthToken.createCriteria().count {
            if (!tokenAdmin) {
                eq("creator", u.login)
            }
        }

        int max = (params.max && params.max.isInteger()) ? params.max.toInteger() :
                grailsApplication.config.getProperty(
                        "rundeck.gui.user.profile.paginatetoken.max.per.page",
                        Integer.class,
                        DEFAULT_TOKEN_PAGE_SIZE)

        int offset = (params.offset && params.offset.isInteger()) ? params.offset.toInteger() : 0

        if(offset >= tokenTotal) {
            def diff = (tokenTotal % max)
            if( diff == 0 && tokenTotal > 0) {
                diff = max
            }
            offset = tokenTotal - diff
        }

        def tokenList = AuthToken.createCriteria().list {
            if (!tokenAdmin) {
                eq("creator", u.login)
            }
            if (offset) {
                firstResult(offset)
            }
            if (max) {
                maxResults(max)
            }<commit_msg>Fix api token total count on user profile page.<commit_after>/*
 * Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package rundeck.controllers

import com.dtolabs.rundeck.core.authentication.tokens.AuthTokenType
import com.dtolabs.rundeck.core.authorization.AuthContext
import com.dtolabs.rundeck.core.authorization.UserAndRolesAuthContext
import com.dtolabs.rundeck.server.authorization.AuthConstants
import grails.converters.JSON
import grails.core.GrailsApplication
import org.rundeck.util.Sizes
import rundeck.AuthToken
import rundeck.Execution
import rundeck.User
import com.dtolabs.rundeck.app.api.ApiVersions
import rundeck.services.FrameworkService
import rundeck.services.UserService

import javax.servlet.http.HttpServletResponse

class UserController extends ControllerBase{

    private static final int DEFAULT_TOKEN_PAGE_SIZE = 50

    UserService userService
    FrameworkService frameworkService
    GrailsApplication grailsApplication
    def apiService
    def configurationService

    static allowedMethods = [
            addFilterPref      : 'POST',
            store              : 'POST',
            update             : 'POST',
            clearApiToken      : 'POST',
            generateUserToken  : 'POST',
            renderUsertoken    : 'POST',
            removeExpiredTokens: 'POST',
            apiUserData        : ['GET','POST'],
            apiUserList        : 'GET'
    ]

    def index = {
        redirect(action:"login")
    }

    def error = {
        flash.loginerror = message(code: "invalid.username.and.password")
        return render(view:'login')
    }

    def logout = {
        session.invalidate()
        return redirect(action: 'loggedout')
    }

    def loggedout(){
        if(grailsApplication.config.rundeck.security.authorization.preauthenticated.redirectLogout in ['true',true]) {
            return redirect(url: grailsApplication.config.grails.serverURL + grailsApplication.config.rundeck.security.authorization.preauthenticated.redirectUrl)
        }
    }

    def login = {
        if (session.user) {
            redirect(controller:'menu', action:'index')
        }
    }

    def denied={
        response.setStatus(403)
        renderErrorView('Access denied')
    }
    def deniedFragment={
        response.setStatus(403)
        renderErrorFragment('Access denied')
    }
    def list={
        AuthContext authContext = frameworkService.getAuthContextForSubject(session.subject)
        if(unauthorizedResponse(frameworkService.authorizeApplicationResourceType(authContext, AuthConstants.TYPE_USER,
                AuthConstants.ACTION_ADMIN),
                AuthConstants.ACTION_ADMIN, 'User', 'accounts')) {
            return
        }
        [users:User.listOrderByLogin()]
    }

    def profile() {
        //check auth to view profile
        //default to current user profile
        if (!params.login) {
            params.login = session.user
        }
        UserAndRolesAuthContext authContext = frameworkService.getAuthContextForSubject(session.subject)

        def tokenAdmin = frameworkService.authorizeApplicationResourceType(
                authContext,
                AuthConstants.TYPE_USER,
                AuthConstants.ACTION_ADMIN)

        if (unauthorizedResponse(
                params.login == session.user || tokenAdmin,
                AuthConstants.ACTION_ADMIN, 'Users', params.login)) {
            return
        }

        def User u = User.findByLogin(params.login)
        if (!u && params.login == session.user) {
            //redirect to profile edit page, so user can setup their profile
            flash.message = "Please fill out your profile"
            return redirect(action: 'register')
        }
        if (notFoundResponse(u, 'User', params['login'])) {
            return
        }

        def tokenTotal = AuthToken.createCriteria().count {
            if (!tokenAdmin) {
                eq("creator", u.login)
            }
            eq("type", AuthTokenType.USER)
        }

        int max = (params.max && params.max.isInteger()) ? params.max.toInteger() :
                grailsApplication.config.getProperty(
                        "rundeck.gui.user.profile.paginatetoken.max.per.page",
                        Integer.class,
                        DEFAULT_TOKEN_PAGE_SIZE)

        int offset = (params.offset && params.offset.isInteger()) ? params.offset.toInteger() : 0

        if(offset >= tokenTotal) {
            def diff = (tokenTotal % max)
            if( diff == 0 && tokenTotal > 0) {
                diff = max
            }
            offset = tokenTotal - diff
        }

        def tokenList = AuthToken.createCriteria().list {
            if (!tokenAdmin) {
                eq("creator", u.login)
            }
            if (offset) {
                firstResult(offset)
            }
            if (max) {
                maxResults(max)
            }
{'fraction_non_alphanumeric': 0.09022625263350738, 'fraction_numerical': 0.0034808097462672894, 'mean_word_length': 2.1895997662868827, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '535772', 'n_tokens_mistral': 2889, 'n_tokens_neox': 2765, 'n_words': 662}