views.py 17.3 KB
Newer Older
Muhamad's avatar
Muhamad committed
1

reynaldi adriantama's avatar
reynaldi adriantama committed
2
from django.db.models.expressions import F
Muhamad's avatar
Muhamad committed
3
from django.http import request, response
reynaldi adriantama's avatar
reynaldi adriantama committed
4 5
from django.views import View, generic
from django.shortcuts import render
reynaldi adriantama's avatar
reynaldi adriantama committed
6
from django.contrib import messages
reynaldi adriantama's avatar
reynaldi adriantama committed
7
from django.contrib.auth.views import LoginView, LogoutView
reynaldi adriantama's avatar
reynaldi adriantama committed
8
from django.db import connection as conn, models
reynaldi adriantama's avatar
reynaldi adriantama committed
9
from django.core import serializers
reynaldi adriantama's avatar
reynaldi adriantama committed
10 11 12 13 14 15
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

reynaldi adriantama's avatar
reynaldi adriantama committed
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38


# 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):
        with conn.cursor() as userlist_:

Muhamad's avatar
Muhamad committed
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
            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)
            
            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()
reynaldi adriantama's avatar
reynaldi adriantama committed
107 108 109 110 111
        
        user_res = []
        for rows in allUser:
            datas = {
                "id": rows[0],
Muhamad's avatar
Muhamad committed
112 113 114 115 116 117
                "username": rows[1],
                "name": rows[2] +" "+ rows[3],
                "email": rows[6],
                "isactive": rows[4],
                "last": rows[5],
                "group": rows[7]
reynaldi adriantama's avatar
reynaldi adriantama committed
118 119 120
            }
            user_res.append(datas)

Muhamad's avatar
Muhamad committed
121 122 123 124
        if request.user.is_superuser:
            with conn.cursor() as grouplist_:
                grouplist_.execute("SELECT * FROM auth_group ORDER BY name ASC")
                allGroup = grouplist_.fetchall()
125

Muhamad's avatar
Muhamad committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
            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)
reynaldi adriantama's avatar
reynaldi adriantama committed
145 146 147
        
        context = {
            'title' : 'user management',
148 149
            'data'  : user_res,
            'dataGroup' : group_res
reynaldi adriantama's avatar
reynaldi adriantama committed
150
        } 
reynaldi adriantama's avatar
reynaldi adriantama committed
151

Muhamad's avatar
Muhamad committed
152
        
reynaldi adriantama's avatar
reynaldi adriantama committed
153 154
        return render(request, self.template_name, context)

reynaldi adriantama's avatar
reynaldi adriantama committed
155 156 157 158 159 160 161 162 163 164 165 166
@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')
Muhamad's avatar
Muhamad committed
167 168 169 170
        isStaff     = request.POST.get('isStaff')

        # arrGroup    = group.split("~")

reynaldi adriantama's avatar
reynaldi adriantama committed
171 172
        
        user = User()
Muhamad's avatar
Muhamad committed
173 174
        # print("ini stag")
        # print(isStaff)
reynaldi adriantama's avatar
reynaldi adriantama committed
175 176 177 178 179 180 181 182 183 184
        # 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)
Muhamad's avatar
Muhamad committed
185 186 187
                
                insertgroups = Group.objects.get(name=group)
                insertgroups.user_set.add(users)
reynaldi adriantama's avatar
reynaldi adriantama committed
188 189 190 191 192 193 194 195

                data = {
                    "code" : 0,
                    "data" : "User telah diperbaharui.",
                    "info" : "success"
                }
            else:
                user = User.objects.get(username=usernames)
Muhamad's avatar
Muhamad committed
196
                # print(user)
reynaldi adriantama's avatar
reynaldi adriantama committed
197 198 199 200 201 202 203
                data = {
                    "code" : 4,
                    "data" : "username telah tersedia, silahkan coba lagi.",
                    "info" : "failed"
                }

        except User.DoesNotExist:
Muhamad's avatar
Muhamad committed
204 205 206 207 208
            # print()
            if isStaff == "true":
                user.is_staff = True
            else:
                user.is_staff = False
reynaldi adriantama's avatar
reynaldi adriantama committed
209 210 211 212 213 214 215
            user.username    = usernames
            user.first_name  = first_name
            user.last_name   = last_name
            user.email       = email
            user.password    = make_password(password)
            user.save()
            
Muhamad's avatar
Muhamad committed
216
            
reynaldi adriantama's avatar
reynaldi adriantama committed
217 218
            # add user to group
            userinsert   = User.objects.get(username=usernames)
Muhamad's avatar
Muhamad committed
219 220 221 222
            
            
            insertgroups = Group.objects.get(name=group)
            insertgroups.user_set.add(userinsert)
reynaldi adriantama's avatar
reynaldi adriantama committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236

            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":

Muhamad's avatar
Muhamad committed
237 238 239 240 241 242 243 244 245 246 247 248
        # 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
reynaldi adriantama's avatar
reynaldi adriantama committed
249
            
Muhamad's avatar
Muhamad committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
            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)
reynaldi adriantama's avatar
reynaldi adriantama committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        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)
Muhamad's avatar
Muhamad committed
295 296 297
        # # print(type(status)+status)
        # # print(type(True))
        # print(status == 'True')
reynaldi adriantama's avatar
reynaldi adriantama committed
298 299 300 301 302 303 304 305
        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)
        
Muhamad's avatar
Muhamad committed
306 307
        # print ("UPDATE auth_user SET is_active = '"+sql+"' WHERE id = "+ids)
        # print (affected_row)
reynaldi adriantama's avatar
reynaldi adriantama committed
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
        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')

Muhamad's avatar
Muhamad committed
340
        # print(id)
reynaldi adriantama's avatar
reynaldi adriantama committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
        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],
Muhamad's avatar
Muhamad committed
356 357
                "group"    : group_res,
                "is_staff" : rows[9]
reynaldi adriantama's avatar
reynaldi adriantama committed
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
            }
            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()

Muhamad's avatar
Muhamad committed
376
    # print(result)
reynaldi adriantama's avatar
reynaldi adriantama committed
377 378 379 380
    resGroup = []
    for i in result:
        resGroup.append(i[0])
    
Muhamad's avatar
Muhamad committed
381
    # print(resGroup)
382 383 384 385 386 387 388 389
    return resGroup

@api_view(('POST',))
def addGroup(request):
    
    if request.method == "POST":
        name    = request.POST.get('name')
        idgroup = request.POST.get('id')
Muhamad's avatar
Muhamad committed
390
        parent  = request.POST.get('parent')
391
        
Muhamad's avatar
Muhamad committed
392 393 394 395 396 397 398 399
        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)
400 401 402
        try:
            if idgroup:
                with conn.cursor() as cursor:
Muhamad's avatar
Muhamad committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
                    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
419

Muhamad's avatar
Muhamad committed
420 421 422 423 424 425 426 427 428 429 430 431 432
                
                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"
                    }
433 434 435 436
            else:
                group = Group.objects.get(name=name)
                data  = {
                    "code" : 4,
Muhamad's avatar
Muhamad committed
437
                    "data" : "Group telah tersedia dalam database.",
438 439 440 441
                    "info" : "failed"
                }

        except Group.DoesNotExist:
Muhamad's avatar
Muhamad committed
442 443 444 445 446
            
            with conn.cursor() as cursor:
                cursor.execute("INSERT INTO auth_group(name, have_parent) VALUES ('"+name+"', "+str(userGroup)+")")
                result = cursor.rowcount
            if result > 0:
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
                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"
            }
        

Muhamad's avatar
Muhamad committed
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
    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)