views.py 18.7 KB
Newer Older
Muhamad's avatar
Muhamad committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626

from django.db.models.expressions import F
from django.http import request, response
from django.views import View, generic
from django.shortcuts import render
from django.contrib import messages
from django.contrib.auth.views import LoginView, LogoutView
from django.db import connection as conn, models
from django.core import serializers
from django.contrib.auth.models import User,Group
from django.contrib.auth.hashers import make_password
from rest_framework import status
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response


def get_per_user(req):
    us = req
    id = us.id
    with conn.cursor() as perm:
        perm.execute("""SELECT
                            json_build_object ( 'kab', gpk.kabupaten, 'pro', gpk.provinsi, 'id_apps', uaa.id_apps, 'apps', uaa.NAME )
                        FROM
                            user_apps_access uaa
                            JOIN geo_prov_kab gpk ON uaa.id_kab = gpk.id_kabupaten 
                        WHERE
                            uaa.id_user = %s"""% id)
        per = perm.fetchall()
        
    permm = per[0][0]
    
    return us, permm

def ui_params(id_app):
    with conn.cursor() as perm:
        perm.execute("""SELECT
                            json_build_object ( 'title', v1, 'logo', v2)
                        FROM
                            ui_params
                        WHERE
                            id_apps = %s"""% int(id_app))
        per = perm.fetchall()
        
    permm = per[0][0]
    return permm


# Create your views here.
class CustomLoginView(LoginView):
    template_name = 'user/login.html'
    redirect_authenticated_user = True

class HomeView(View):
    template_name = 'layout/layout.html'

    def get(self, request):
        return render(request, self.template_name)

class CustomLogoutView(LogoutView):
    template_name = 'user/login.html'
    next_page = 'login'

class Usermanagement(generic.TemplateView):
    template_name = "layout/user_layout.html"
    
    def get(self, request):
        usern, perm = get_per_user(request.user)
        kab = perm['kab']
        # print(perm)
        ui_param = ui_params(perm['id_apps'])
        title = ui_param['title']
        logo = ui_param['logo']
        print(type(request.user.groups.all()))

        with conn.cursor() as userlist_:
            # if request.user.groups.all() == ''
            arrayGroups = []

            for g in request.user.groups.all():
                print(g)
                userGroup = g.id
            
            
                arrayGroups.append(userGroup)
                isChild = isHaveChild(userGroup)

                if isChild == True:
                    childgroup = getGroupChilds(userGroup)
                    for z in childgroup['data']:
                        arrayGroups.append(z[0])
                    
                    ars = ",".join(str(v) for v in arrayGroups)
                
                else:
                    ars = "".join(str(v) for v in arrayGroups)

            
            # print(ars)
            if request.user.is_superuser:
                # print("is superuser")
                sql = """
                        SELECT
                        au.id,
                        au.username,
                        au.first_name,
                        au.last_name,
                        au.is_active,
                        au.last_login,
                        au.email,
                        ag.name,
                        au.is_staff,
                        au.is_superuser
                    FROM
                        auth_user au,
                        auth_user_groups aug,
                        auth_group ag
                    WHERE
                        au.id = aug.user_id AND
                        ag.id = aug.group_id
                    ORDER BY 
                        au.username ASC"""
            else:
                if request.user.is_staff:
                     sql = """
                        SELECT
                        au.id,
                        au.username,
                        au.first_name,
                        au.last_name,
                        au.is_active,
                        au.last_login,
                        au.email,
                        ag.name,
                        au.is_staff,
                        au.is_superuser
                    FROM
                        auth_user au,
                        auth_user_groups aug,
                        auth_group ag
                    WHERE
                        au.id = aug.user_id AND
                        ag.id = aug.group_id AND  
                        ag.id IN("""+ars+")"
                else:
                    print('not staff')
            userlist_.execute(sql)
            allUser = userlist_.fetchall()
        
        user_res = []
        for rows in allUser:
            datas = {
                "id": rows[0],
                "username": rows[1],
                "name": rows[2] +" "+ rows[3],
                "email": rows[6],
                "isactive": rows[4],
                "last": rows[5],
                "group": rows[7]
            }
            user_res.append(datas)

        if request.user.is_superuser:
            with conn.cursor() as grouplist_:
                grouplist_.execute("SELECT * FROM auth_group ORDER BY name ASC")
                allGroup = grouplist_.fetchall()

            group_res = []
            for rows in allGroup:
                datas = {
                    "id" : rows[0],
                    "name" : rows[1],
                }
                group_res.append(datas)
        else:
            with conn.cursor() as grouplist_:
                grouplist_.execute("SELECT * FROM auth_group WHERE id IN("+ars+")ORDER BY name ASC")
                allGroup = grouplist_.fetchall()

            group_res = []
            for rows in allGroup:
                datas = {
                    "id" : rows[0],
                    "name" : rows[1],
                }
                group_res.append(datas)
        parameter_ui = {'logo':logo, 'title':title}
        context = {
            'title' : 'user management',
            'data'  : user_res,
            'dataGroup' : group_res,
            'title' : title,
            'logo' : logo,
            'parameter_ui':parameter_ui,
        } 

        
        return render(request, self.template_name, context)

@api_view(('POST',))
def addUser(request):
    
    if request.method == 'POST':
        
        usernames   = request.POST.get('username')
        first_name  = request.POST.get('first_name')
        last_name   = request.POST.get('last_name')
        group       = request.POST.get('group')
        email       = request.POST.get('email')
        password    = request.POST.get('username')
        iduser      = request.POST.get('id')
        isStaff     = request.POST.get('isStaff')

        # arrGroup    = group.split("~")

        
        user = User()
        # print("ini stag")
        # print(isStaff)
        # user.save()
        try:
            if iduser:
                with conn.cursor() as cursor:
                    cursor.execute("UPDATE auth_user SET first_name = '"+first_name+"', last_name = '"+last_name+"', email = '"+email+"' WHERE id="+iduser)
                
                with conn.cursor() as curGroup:
                    curGroup.execute("DELETE FROM auth_user_groups WHERE user_id="+iduser)

                users = User.objects.get(username=usernames)
                
                insertgroups = Group.objects.get(name=group)
                insertgroups.user_set.add(users)

                data = {
                    "code" : 0,
                    "data" : "User telah diperbaharui.",
                    "info" : "success"
                }
            else:
                user = User.objects.get(username=usernames)
                # print(user)
                data = {
                    "code" : 4,
                    "data" : "username telah tersedia, silahkan coba lagi.",
                    "info" : "failed"
                }

        except User.DoesNotExist:
            # print()
            if isStaff == "true":
                user.is_staff = True
            else:
                user.is_staff = False
            user.username    = usernames
            user.first_name  = first_name
            user.last_name   = last_name
            user.email       = email
            user.password    = make_password(password)
            user.save()
            
            
            # add user to group
            userinsert   = User.objects.get(username=usernames)
            
            
            insertgroups = Group.objects.get(name=group)
            insertgroups.user_set.add(userinsert)

            data = {
                "code" : 0,
                "info" : "success",
                "data" : "user "+usernames+" berhasil ditambahkan"
            }
    
    # data = {'sukses':'sukses'}
    return Response(data)

@api_view(('POST',))
def listGroup(request):
    if request.method == "POST":

        # print(request.user.is_superuser)
        
        if request.user.is_superuser:
            groupList = Group.objects.all().order_by('name')
            # # print(groupList)

            group = []
            for g in groupList:
                group.append(g.name)
        else:
            for g in request.user.groups.all():
                userGroup = g.id
            
            arrayGroups = []
            arrayGroups.append(userGroup)
            isChild = isHaveChild(userGroup)

            if isChild == True:
                childgroup = getGroupChilds(userGroup)
                for z in childgroup['data']:
                    arrayGroups.append(z[0])
                
                ars = ",".join(str(v) for v in arrayGroups)
            
            groupList = Group.objects.all().order_by('name')
            # # print("ini gl")
            # # print(groupList)
        
            group = []
            for g in groupList:
                for i in arrayGroups:
                    if i == g.id:
                        group.append(g.name)
        # print(group)
        if len(group) > 0:
            data = {
                "info" : "success",
                "code" : 0,
                "data" : group
            }
        else:
            data = {
                "info" : "group tidak tersedia",
                "code" : 4,
                "data" : group
            }

    return Response(data)

@api_view(('POST',))
def deactivateUser(request):
    
    user = User()
    if request.method == "POST":
        ids     = request.POST.get('id')
        status  = request.POST.get('stat')

        isActive = loadUserStatus(ids)
        # # print(type(status)+status)
        # # print(type(True))
        # print(status == 'True')
        if status == 'True':
            sql = "f"
        else:
            sql = "t"

        with conn.cursor() as cursor:
            affected_row = cursor.execute("UPDATE auth_user SET is_active = '"+sql+"' WHERE id = "+ids)
        
        # print ("UPDATE auth_user SET is_active = '"+sql+"' WHERE id = "+ids)
        # print (affected_row)
        if affected_row:
            data = {
                "info" : "success",
                "code" : 0,
                "data" : "User berhasil dinonaktifkan"
            }
        else:
            data = {
                "info" : "success",
                "code" : 0,
                "data" : "User berhasil dinonaktifkan"
            }

    return Response(data)


def loadUserStatus(id):

    with conn.cursor() as cursor:
        cursor.execute("SELECT is_active from auth_user WHERE id="+id+"")
        resData = cursor.fetchall()

    for i in resData:
        isActive = i[0]
    
    return isActive

@api_view(('POST',))
def loadUserbyId(request):
    if request.method == "POST":
        id = request.POST.get('id')

        # print(id)
        with conn.cursor() as cursor:
            cursor.execute("SELECT * FROM auth_user WHERE id ="+id)
            result = cursor.fetchall()

        group_res = loadGroupById(id)
        user_res  = []
        for rows in result:
            datas = {
                "id"       : rows[0],
                "username" : rows[4],
                "firstname": rows[5],
                "lastname" : rows[6],
                "email"    : rows[7],
                "isactive" : rows[9],
                "last"     : rows[2],
                "group"    : group_res,
                "is_staff" : rows[9]
            }
            user_res.append(datas)

        data = {
            "info" : "success",
            "code" : 0,
            "data" : datas,
        }
        

    return Response(data)

def loadGroupById(iduser):

    with conn.cursor() as cursor:
        cursor.execute("select ag.name from auth_group ag, auth_user_groups aug WHERE aug.user_id = "+iduser+" AND ag.id = aug.group_id")
        result = cursor.fetchall()

    # print(result)
    resGroup = []
    for i in result:
        resGroup.append(i[0])
    
    # print(resGroup)
    return resGroup

@api_view(('POST',))
def addGroup(request):
    
    if request.method == "POST":
        name    = request.POST.get('name')
        idgroup = request.POST.get('id')
        parent  = request.POST.get('parent')
        
        if parent != None:
            for s in Group.objects.all():
                if s.name == parent:
                    userGroup = s.id
        else:
            for g in request.user.groups.all():
                userGroup = g.id 
        # # print(userGroup)
        try:
            if idgroup:
                with conn.cursor() as cursor:
                    cursor.execute("SELECT have_parent FROM auth_group WHERE id="+str(idgroup))
                    result = cursor.fetchall()
                
                for row in result:
                    isParent = row[0]
                
                # print("ini parent ya gan")
                # print(len(result))
                if isParent == None:
                    with conn.cursor() as cursor:
                        cursor.execute("UPDATE auth_group SET name = '"+name+"' WHERE id="+str(idgroup))
                        result = cursor.rowcount
                else:
                    with conn.cursor() as cursor:
                        cursor.execute("UPDATE auth_group SET name = '"+name+"', have_parent = '"+str(userGroup)+"' WHERE id="+str(idgroup))
                        result = cursor.rowcount

                
                if result > 0:
                    data = {
                        "code" : 0,
                        "data" : "Group telah diperbaharui.",
                        "info" : "success"
                    }
                else:
                    data = {
                        "code" : 4,
                        "data" : "Group gagal diperbaharui, silahkan coba beberapa saat lagi",
                        "info" : "failed"
                    }
            else:
                group = Group.objects.get(name=name)
                data  = {
                    "code" : 4,
                    "data" : "Group telah tersedia dalam database.",
                    "info" : "failed"
                }

        except Group.DoesNotExist:
            
            with conn.cursor() as cursor:
                cursor.execute("INSERT INTO auth_group(name, have_parent) VALUES ('"+name+"', "+str(userGroup)+")")
                result = cursor.rowcount
            if result > 0:
                data = {
                    "code" : 0,
                    "info" : "success",
                    "data" : "Group berhasil ditambahkan"
                }
            else:
                data = {
                    "code" : 4,
                    "info" : "failed",
                    "data" : "Group gagal ditambahkan"
                }

    return Response(data)

@api_view(('POST',))
def deleteGroup(request):

    if request.method == "POST":
        id = request.POST.get('id')

        with conn.cursor() as cursor:
            cursor.execute("DELETE FROM auth_group WHERE id="+id)
            result = cursor.rowcount

        if result > 0:
            data = {
                "code" : 0,
                "info" : "success",
                "data" : "data berhasil dihapus"
            }
        else:
            data = {
                "code" : 4,
                "info" : "success",
                "data" : "data berhasil dihapus"
            }
        

    return Response(data)

def getGroupChilds(groupid):
    with conn.cursor() as cursor:
        cursor.execute("SELECT id FROM auth_group WHERE have_parent="+str(groupid))
        # print("query")
        # print("SELECT id FROM auth_group WHERE have_parent="+str(groupid))
        result = cursor.fetchall()
        # print("lastrow")
        # print(result[0])


        resultArray = []
        for i in result:
            resultArray.append(i)
            id = i
        
        vasrt = len(result)
        id    = id[0]
        # print(vasrt)
        # print("ini id")
        # print(id)

        while vasrt != 0:
            cursor.execute("SELECT id FROM auth_group WHERE have_parent="+str(id))
            resd = cursor.fetchall()

            # print("q res")
            # print(len(resd))
            for z in resd:
                resultArray.append(z)
                id = z[0]
                
            vasrt = len(resd)
        
        data = {
            'data' : resultArray
        }
        # print(data)
        
    return data

def isHaveChild(id):
    result = False

    with conn.cursor() as cursor:
        cursor.execute("SELECT * FROM auth_group WHERE have_parent ="+str(id))
        data = cursor.fetchall()

    if len(data) > 0:
        result = True
    
    return result

@api_view(('POST',))
def loadGroupByGroupId(request):
    if request.method == "POST":
        idgroup = request.POST.get('id')
        with conn.cursor() as cursor:
            sql = "SELECT * FROM auth_group WHERE id="+idgroup
            cursor.execute(sql)
            result = cursor.fetchall()
        
        
        arrdata = []
        for row in result:
            idparent = row[3]
            arrdata.append(row)
            
        
        if len(arrdata) > 0:

            if idparent != None:
                with conn.cursor() as cursor:
                    sql = "SELECT name FROM auth_group WHERE id = "+str(idparent)
                    cursor.execute(sql)
                    res = cursor.fetchall()
                
                arrname = []
                for x in res:
                    arrname.append(x[0])
            else:
                arrname = []
            

            data = {
                "code": 0,
                "info": "success",
                "data": arrname ,
                
            }
        else:
            data = {
                "code": 4,
                "info": "failed",
                "data": "group tidak memiliki parent" 
            }
    return Response(data)